-
Notifications
You must be signed in to change notification settings - Fork 10
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
feat:register vesting type, add support for delegation/undelegation of native token #127
feat:register vesting type, add support for delegation/undelegation of native token #127
Conversation
WalkthroughThe recent updates introduce significant enhancements to the Exocore Network's codebase, focusing on the integration of the vesting module and improvements to asset management and delegation functionalities. Key changes include the addition of new constants for native assets, the introduction of CLI commands for delegating and undelegating tokens, and the restructuring of delegation-related messages. These modifications streamline asset interactions for stakers and enhance the overall delegation process. Changes
Possibly related PRs
Suggested reviewers
Poem
Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media? TipsChatThere are 3 ways to chat with CodeRabbit:
Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments. CodeRabbit Commands (Invoked using PR comments)
Other keywords and placeholders
CodeRabbit Configuration File (
|
parsedStakerID := strings.Split(record.StakerID, "-") | ||
stakerAddr := sdk.AccAddress(hexutil.MustDecode(parsedStakerID[0])) | ||
if err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, types.DelegatedPoolName, stakerAddr, sdk.NewCoins(sdk.NewCoin(assetstypes.NativeAssetDenom, record.ActualCompletedAmount))); err != nil { | ||
panic(err) |
Check warning
Code scanning / CodeQL
Panic in BeginBock or EndBlock consensus methods Warning
WaitUnbondingAmount: recordAmountNeg, | ||
}) | ||
if err != nil { | ||
panic(err) |
Check warning
Code scanning / CodeQL
Panic in BeginBock or EndBlock consensus methods Warning
parsedStakerID := strings.Split(record.StakerID, "-") | ||
stakerAddr := sdk.AccAddress(hexutil.MustDecode(parsedStakerID[0])) | ||
if err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, types.DelegatedPoolName, stakerAddr, sdk.NewCoins(sdk.NewCoin(assetstypes.NativeAssetDenom, record.ActualCompletedAmount))); err != nil { | ||
panic(err) |
Check warning
Code scanning / CodeQL
Panic in BeginBock or EndBlock consensus methods Warning
WaitUnbondingAmount: recordAmountNeg, | ||
}) | ||
if err != nil { | ||
panic(err) |
Check warning
Code scanning / CodeQL
Panic in BeginBock or EndBlock consensus methods Warning
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
Outside diff range and nitpick comments (1)
x/delegation/keeper/abci.go (1)
Line range hint
41-85
:
Replacepanic
with proper error handling.Using
panic
in theEndBlock
function can cause the chain to halt. Replacepanic
with proper error handling to ensure the stability of the application.- if err != nil { - panic(err) - } + if err != nil { + k.Logger(ctx).Error("Failed to update staker asset state", "error", err) + continue + } - if err != nil { - panic(err) - } + if err != nil { + k.Logger(ctx).Error("Failed to update operator asset state", "error", err) + continue + } - if err != nil { - panic(err) - } + if err != nil { + k.Logger(ctx).Error("Failed to delete undelegation record", "error", err) + continue + }Tools
GitHub Check: CodeQL
[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt
[warning] 84-84: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt
[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic call
[warning] 84-84: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic call
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (10)
- app/app.go (8 hunks)
- x/assets/types/general.go (1 hunks)
- x/delegation/keeper/abci.go (4 hunks)
- x/delegation/keeper/cross_chain_tx_process.go (1 hunks)
- x/delegation/keeper/delegation_state.go (1 hunks)
- x/delegation/keeper/keeper.go (1 hunks)
- x/delegation/keeper/un_delegation_state.go (1 hunks)
- x/delegation/types/cross_chain_params.go (1 hunks)
- x/delegation/types/expected_keepers.go (1 hunks)
- x/delegation/types/general.go (1 hunks)
Files skipped from review due to trivial changes (3)
- x/delegation/keeper/keeper.go
- x/delegation/keeper/un_delegation_state.go
- x/delegation/types/general.go
Additional context used
GitHub Check: CodeQL
x/delegation/keeper/abci.go
[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt
[warning] 84-84: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt
[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic call
[warning] 84-84: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic call
Additional comments not posted (8)
x/delegation/types/cross_chain_params.go (1)
22-42
: LGTM! But verify the function usage in the codebase.The code changes are approved.
However, ensure that all function calls to
NewDelegationOrUndelegationParams
match the new signature.x/delegation/types/expected_keepers.go (1)
55-59
: LGTM! But verify the interface implementation.The code changes are approved.
However, ensure that all implementations of the
BankKeeper
interface include the new methods.x/assets/types/general.go (1)
14-21
: LGTM!The addition of constants for native assets improves code readability and maintainability.
x/delegation/keeper/cross_chain_tx_process.go (1)
41-64
: Ensure Correctness of Native Asset Handling.The new logic for handling native assets looks correct, but verify the following:
- Ensure
assetstype.NativeAssetID
andassetstype.NativeAssetDenom
are correctly defined.- Confirm
DelegateCoinsFromAccountToModule
correctly handles the transfer of native assets.- Ensure all necessary tests are updated or added for this new logic.
x/delegation/keeper/delegation_state.go (1)
149-149
: Verify Consistency of Updated Error Handling.The updated error handling method using
delegationtype.ErrNoKeyInTheStore.Wrapf
looks correct. Ensure this method is consistently used across the codebase for error wrapping.app/app.go (3)
123-124
: Verify Necessity and Correctness of New Imports.The imports for
vesting
andvestingtypes
are added. Ensure these are necessary for the new functionalities and correctly imported.
259-259
: Ensure Correct Integration ofvesting.AppModuleBasic{}
.The addition of
vesting.AppModuleBasic{}
to the module list looks correct. Verify that this integration is necessary and correctly implemented.
292-293
: Verify Integration ofvestingtypes.ModuleName
.The integration of
vestingtypes.ModuleName
in theNewExocoreApp
function looks correct. Ensure this integration is necessary and correctly implemented.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (16)
- app/app.go (11 hunks)
- testutil/utils.go (1 hunks)
- x/assets/keeper/expected_keepers.go (1 hunks)
- x/assets/keeper/keeper.go (1 hunks)
- x/assets/keeper/staker_asset.go (2 hunks)
- x/assets/types/expected_keepers.go (1 hunks)
- x/assets/types/general.go (1 hunks)
- x/delegation/client/cli/tx.go (1 hunks)
- x/delegation/client/cli/tx_delegation_native.go (1 hunks)
- x/delegation/keeper/abci.go (4 hunks)
- x/delegation/keeper/delegation_op_test.go (7 hunks)
- x/delegation/keeper/keeper.go (2 hunks)
- x/delegation/keeper/msg_server.go (1 hunks)
- x/delegation/keeper/setup_test.go (2 hunks)
- x/delegation/types/expected_keepers.go (1 hunks)
- x/delegation/types/msg.go (2 hunks)
Files skipped from review due to trivial changes (3)
- testutil/utils.go
- x/assets/keeper/expected_keepers.go
- x/assets/types/expected_keepers.go
Files skipped from review as they are similar to previous changes (5)
- app/app.go
- x/assets/types/general.go
- x/delegation/keeper/abci.go
- x/delegation/keeper/keeper.go
- x/delegation/types/expected_keepers.go
Additional comments not posted (5)
x/delegation/keeper/setup_test.go (1)
23-23
: Verify the usage of the new fieldaccAddr
.Ensure that the newly added field
accAddr
is properly utilized in the test suite. It's important to check if it's being set and used correctly in the tests to prevent any issues during runtime.Verification successful
The field
accAddr
is properly utilized in the test suite.The field
accAddr
is set and used in thex/delegation/keeper/delegation_op_test.go
file, confirming its integration into the test cases.
x/delegation/keeper/delegation_op_test.go
: Proper setting and usage ofaccAddr
.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the usage of the new field `accAddr` in the test suite. # Test: Search for the field usage. Expect: Proper setting and usage in the test methods. rg --type go -A 5 $'accAddr' x/delegation/keeper/setup_test.goLength of output: 166
Script:
#!/bin/bash # Description: Search for all occurrences of the field `accAddr` in the test suite file to verify its usage. # Test: Search for the field usage. Expect: Proper setting and usage in the test methods. rg 'accAddr' x/delegation/keeper/setup_test.goLength of output: 79
Script:
#!/bin/bash # Description: Search for all occurrences of the field `accAddr` in the `x/delegation/keeper` directory to verify its usage. # Test: Search for the field usage. Expect: Proper setting and usage in the test methods. rg 'accAddr' x/delegation/keeperLength of output: 932
x/delegation/client/cli/tx_delegation_native.go (1)
16-46
: Command structure and error handling look good.The structure of the
CmdDelagateNativeToken
command and its error handling are well implemented. The usage ofsdkmath
for amount validation and the comprehensive error messages enhance the robustness of the command.x/delegation/types/msg.go (1)
29-41
: Verify the integration and usage of the new message typeMsgDelegation
.Ensure that the new message type
MsgDelegation
is properly integrated and used throughout the system. It's important to check that theValidateBasic
method is called whenever the message is created to ensure data integrity.Verification successful
The
MsgDelegation
message type is properly integrated and itsValidateBasic
method is called to ensure data integrity.
x/delegation/client/cli/tx_delegation_native.go
: TheValidateBasic
method is called to validateMsgDelegation
.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the integration and usage of the new message type `MsgDelegation`. # Test: Search for the message type usage and the `ValidateBasic` method call. Expect: Proper integration and validation calls. rg --type go -A 5 $'MsgDelegation' --exec rg 'ValidateBasic' {}Length of output: 471
Script:
#!/bin/bash # Step 1: Search for the usage of MsgDelegation and list the files. rg --type go 'MsgDelegation' -l > msg_delegation_usage_files.txt # Step 2: Search for the ValidateBasic method call within those files. while IFS= read -r file; do echo "Searching in $file" rg 'ValidateBasic' "$file" done < msg_delegation_usage_files.txtLength of output: 1352
x/assets/keeper/keeper.go (1)
13-27
: Review ofKeeper
Struct andNewKeeper
Constructor
- Architecture: The addition of
BankKeeper
anddelegationKeeper
to theKeeper
struct is consistent with dependency injection principles, which is good for modularity and testing.- Best Practices: The constructor
NewKeeper
correctly initializes theKeeper
struct with provided dependencies, ensuring that all components are properly set up for use.- Maintainability: The clear separation of concerns and encapsulation of dependencies within the
Keeper
struct enhances maintainability.x/delegation/keeper/delegation_op_test.go (1)
Line range hint
69-452
: Comprehensive Review of Delegation Test Cases
- Correctness: The tests cover both regular and native token delegations, ensuring that the new functionality is properly verified.
- Logic: The tests follow a logical flow of preparing, executing, and verifying the outcomes of delegation and undelegation actions.
- Maintainability: The use of descriptive function names and structured test cases enhances maintainability.
- Performance: Consider mocking external dependencies to speed up the tests, especially if running against live environments.
- Best Practices: The tests are well-structured and provide good coverage of the new functionalities introduced in the PR.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (1)
- x/delegation/keeper/delegation_op_test.go (7 hunks)
Files skipped from review as they are similar to previous changes (1)
- x/delegation/keeper/delegation_op_test.go
app/app.go
Outdated
app.StakingKeeper.OperatorHooks(), | ||
) | ||
|
||
(&app.EpochsKeeper).SetHooks( | ||
app.EpochsKeeper.SetHooks( |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
When fixing conflicts use
epochstypes.NewMultiEpochHooks(
app.StakingKeeper.EpochsHooks(), // at this point, the order is irrelevant.
app.ExomintKeeper.EpochsHooks(), // however, this may change once we have distribution
),
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files ignored due to path filters (1)
x/delegation/types/tx.pb.go
is excluded by!**/*.pb.go
Files selected for processing (11)
- proto/exocore/delegation/v1/tx.proto (2 hunks)
- x/assets/keeper/bank.go (1 hunks)
- x/assets/keeper/staker_asset.go (2 hunks)
- x/delegation/client/cli/tx.go (1 hunks)
- x/delegation/client/cli/tx_delegation_native.go (1 hunks)
- x/delegation/keeper/keeper.go (4 hunks)
- x/delegation/keeper/msg_server.go (1 hunks)
- x/delegation/keeper/share.go (2 hunks)
- x/delegation/types/msg.go (2 hunks)
- x/reward/keeper/claim_reward.go (1 hunks)
- x/slash/keeper/execute_slash.go (6 hunks)
Files skipped from review as they are similar to previous changes (4)
- x/assets/keeper/staker_asset.go
- x/delegation/client/cli/tx_delegation_native.go
- x/delegation/keeper/msg_server.go
- x/delegation/types/msg.go
Additional comments not posted (4)
x/delegation/client/cli/tx.go (1)
21-23
: Addition ofCmdDelegate()
andCmdUndelegate()
commands to CLIThe addition of these commands is consistent with the PR's objective to enhance native token delegation functionality.
x/delegation/keeper/keeper.go (2)
Line range hint
24-44
: Integration ofbankKeeper
intoKeeper
structThe addition of
bankKeeper
to theKeeper
struct is a crucial development, enhancing the module's ability to interact with banking operations directly. This change supports the PR's objectives related to asset management and delegation operations.
68-70
: Addition ofLogger
Method toKeeper
The new
Logger
method enhances debugging and logging capabilities by providing a logger tied to the module's context. This is a beneficial addition for maintaining clarity and traceability in the module's operations.proto/exocore/delegation/v1/tx.proto (1)
Line range hint
62-124
: Modifications intx.proto
for Delegation FunctionalityThe changes in the protobuf definitions, including the use of
repeated KeyValue
instead of a map and the reordering of fields, are significant. These modifications improve the predictability and consistency of data serialization, which is crucial for blockchain operations. The addition ofasset_id
as a field with a custom name directive enhances clarity and specificity in message structures.
// TODO: there should be a reward pool to be transferred from for native tokens' reward, don't update staker-asset-info, just transfer exo-native-token:pool->staker or handled by validators since the reward would be transferred to validators directly. | ||
if assetID != types.NativeAssetID { | ||
err := k.assetsKeeper.UpdateStakerAssetState(ctx, stakeID, assetID, changeAmount) | ||
if err != nil { | ||
return err | ||
} | ||
if err = k.assetsKeeper.UpdateStakingAssetTotalAmount(ctx, assetID, event.OpAmount); err != nil { | ||
return err | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Conditional Logic for Native Tokens in RewardForWithdraw
The conditional logic introduced to handle rewards for native tokens separately seems appropriate given the context of native token management. However, the comment on line 143 suggests that there might be a need for a reward pool transfer mechanism which isn't implemented here.
- Ensure that the logic for handling native tokens aligns with the overall system's token management strategy.
- Consider implementing or clarifying the reward pool transfer mechanism as hinted in the TODO comment.
x/slash/keeper/execute_slash.go
Outdated
// dont't create stakerasset info for native token. | ||
// TODO: do we need to do any other process for native token 'else{}' ? | ||
if assetID != assetstypes.NativeAssetID { | ||
changeAmount := assetstypes.DeltaStakerSingleAsset{ | ||
TotalDepositAmount: event.OpAmount.Neg(), | ||
} | ||
err := k.assetsKeeper.UpdateStakerAssetState(ctx, stakeID, assetID, changeAmount) | ||
if err != nil { | ||
return err | ||
} | ||
if err = k.assetsKeeper.UpdateStakingAssetTotalAmount(ctx, assetID, event.OpAmount.Neg()); err != nil { | ||
return err | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Handling of Native Tokens in Slash
Function
The conditional logic to not create staker asset info for native tokens is a significant change. This aligns with the PR's focus on native token management but raises a few concerns:
- The comment on line 195 asks whether additional processes are needed for native tokens. This needs clarification.
- Ensure that the skipping of asset state updates for native tokens does not lead to inconsistencies in the system's state management.
x/delegation/keeper/share.go
Outdated
// don't update staker asset info for exo-native-token | ||
if assetID != assetstypes.NativeAssetID { | ||
// todo: TotalDepositAmount might be influenced by slash and precision loss, | ||
// consider removing it, it can be recalculated from the share for RPC query. | ||
err = k.assetsKeeper.UpdateStakerAssetState(ctx, stakerID, assetID, assetstype.DeltaStakerSingleAsset{ | ||
WaitUnbondingAmount: removeToken, | ||
}) | ||
if err != nil { | ||
return removeToken, err | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Conditional Logic for Native Tokens in RemoveShare
Function
The introduction of conditional logic to skip updating staker asset state for native tokens is critical for the system's handling of these assets. However, the comment on line 220 suggests reconsidering the calculation of TotalDepositAmount
. This might indicate potential issues with precision loss or other calculation inaccuracies.
- Verify that skipping the update of staker asset state for native tokens is consistent with other parts of the system.
- Address the concern raised about
TotalDepositAmount
to ensure accurate financial calculations.
x/assets/keeper/bank.go
Outdated
// don't update staker info for exo-native-token | ||
// TODO: do we need additional process for exo-native-token ? | ||
if assetID != assetstypes.NativeAssetID { | ||
// update asset state of the specified staker | ||
err = k.UpdateStakerAssetState(ctx, stakeID, assetID, changeAmount) | ||
if err != nil { | ||
return errorsmod.Wrapf(err, "stakeID:%s assetID:%s", stakeID, assetID) | ||
} | ||
|
||
// update total amount of the deposited asset | ||
err = k.UpdateStakingAssetTotalAmount(ctx, assetID, actualOpAmount) | ||
if err != nil { | ||
return errorsmod.Wrapf(err, "assetID:%s", assetID) | ||
// update total amount of the deposited asset | ||
err = k.UpdateStakingAssetTotalAmount(ctx, assetID, actualOpAmount) | ||
if err != nil { | ||
return errorsmod.Wrapf(err, "assetID:%s", assetID) | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Conditional Logic for exo-native-token
in PerformDepositOrWithdraw
The addition of a condition to skip updating staker info for exo-native-token
is a significant change. This logic ensures that operations specific to the native token are handled differently, which is crucial given its unique role in the ecosystem.
However, the TODO
comment indicates uncertainty about whether additional processes are needed for exo-native-token
. It's important to address this to ensure that all necessary operations for the native token are correctly implemented.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 0
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (3)
- x/assets/keeper/staker_asset.go (2 hunks)
- x/assets/types/general.go (1 hunks)
- x/delegation/client/cli/tx_delegation_native.go (1 hunks)
Files skipped from review as they are similar to previous changes (3)
- x/assets/keeper/staker_asset.go
- x/assets/types/general.go
- x/delegation/client/cli/tx_delegation_native.go
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 3
Outside diff range, codebase verification and nitpick comments (4)
x/assets/client/cli/tx.go (3)
Line range hint
26-35
:
Re-add the validation step for robustness.The removal of
msg.ValidateBasic()
can lead to the processing of invalid messages, reducing the function's robustness. It's recommended to re-add the validation step to ensure basic validation of themsg
object.+ if err := msg.ValidateBasic(); err != nil { + return err + }
Line range hint
52-73
:
Re-add the validation step for robustness.The removal of
msg.ValidateBasic()
can lead to the processing of invalid messages, reducing the function's robustness. It's recommended to re-add the validation step to ensure basic validation of themsg
object.+ if err := msg.ValidateBasic(); err != nil { + return err + }
Line range hint
92-119
:
Re-add the validation step for robustness.The removal of
msg.ValidateBasic()
can lead to the processing of invalid messages, reducing the function's robustness. It's recommended to re-add the validation step to ensure basic validation of themsg
object.+ if err := msg.ValidateBasic(); err != nil { + return err + }x/slash/keeper/execute_slash.go (1)
13-15
: Remove commented import.The commented import statement should be removed to keep the code clean.
- // "github.com/ExocoreNetwork/exocore/x/assets/types"
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files ignored due to path filters (1)
x/delegation/types/tx.pb.go
is excluded by!**/*.pb.go
Files selected for processing (10)
- proto/exocore/delegation/v1/tx.proto (3 hunks)
- x/assets/client/cli/tx.go (3 hunks)
- x/assets/keeper/expected_keepers.go (1 hunks)
- x/assets/keeper/staker_asset.go (2 hunks)
- x/assets/keeper/staker_asset_test.go (1 hunks)
- x/delegation/client/cli/tx_delegation_native.go (1 hunks)
- x/delegation/keeper/keeper.go (4 hunks)
- x/delegation/keeper/share.go (1 hunks)
- x/delegation/types/msg.go (2 hunks)
- x/slash/keeper/execute_slash.go (6 hunks)
Additional comments not posted (19)
x/assets/keeper/expected_keepers.go (1)
1-11
: LGTM! But verify the usage of the new interface.The code changes are approved.
However, ensure that the new
delegationKeeper
interface is correctly used in the codebase.Verification successful
The new
delegationKeeper
interface is correctly used in the codebase.The
GetDelegationInfo
method from thedelegationKeeper
interface is utilized in various parts of the code, confirming its proper integration.
x/delegation/keeper/grpc_query.go
x/assets/keeper/staker_asset.go
Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the usage of the new `delegationKeeper` interface. # Test: Search for the interface usage. Expect: Occurrences of the new interface. rg --type go -A 5 $'delegationKeeper'Length of output: 9349
Script:
#!/bin/bash # Description: Verify the usage of the `GetDelegationInfo` method from the `delegationKeeper` interface. # Test: Search for the method usage. Expect: Occurrences of the method call. rg --type go -A 5 $'GetDelegationInfo'Length of output: 4816
x/delegation/types/msg.go (2)
66-79
: LGTM! But verify the usage of the new functionNewMsgUndelegation
.The code changes are approved.
However, ensure that the new
NewMsgUndelegation
function is correctly used in the codebase.Verification successful
The function
NewMsgUndelegation
is correctly used in the codebase.
- The function
NewMsgUndelegation
is utilized inx/delegation/client/cli/tx_delegation_native.go
.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the usage of the new `NewMsgUndelegation` function. # Test: Search for the function usage. Expect: Occurrences of the new function. rg --type go -A 5 $'NewMsgUndelegation'Length of output: 991
27-40
: LGTM! But verify the usage of the new functionNewMsgDelegation
.The code changes are approved.
However, ensure that the new
NewMsgDelegation
function is correctly used in the codebase.x/delegation/client/cli/tx_delegation_native.go (2)
1-39
: LGTM! But verify the usage of the CLI commandCmdDelegate
.The code changes are approved.
However, ensure that the new
CmdDelegate
command is correctly used in the codebase.Verification successful
The
CmdDelegate
command is correctly used in the codebase.
- The command is registered as a subcommand of
txCmd
inx/delegation/client/cli/tx.go
.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the usage of the new `CmdDelegate` command. # Test: Search for the command usage. Expect: Occurrences of the new command. rg --type go -A 5 $'CmdDelegate'Length of output: 829
Script:
#!/bin/bash # Extract the relevant section from tx.go to verify the usage of CmdDelegate. rg --type go -A 10 -B 10 $'CmdDelegate' x/delegation/client/cli/tx.goLength of output: 425
41-66
: LGTM! But verify the usage of the CLI commandCmdUndelegate
.The code changes are approved.
However, ensure that the new
CmdUndelegate
command is correctly used in the codebase.x/delegation/keeper/keeper.go (3)
19-23
: LGTM! The new fields are correctly added to theKeeper
struct.The addition of
accountKeeper
andbankKeeper
fields enhances theKeeper
's functionality by allowing it to manage account and bank-related operations.
33-43
: LGTM! TheNewKeeper
constructor function is correctly updated.The function now accepts
accountKeeper
andbankKeeper
parameters and initializes the corresponding fields in theKeeper
struct.
67-69
: LGTM! TheLogger
method is a valuable addition.The method provides a structured logging mechanism, enhancing the traceability of logs associated with the delegation module.
proto/exocore/delegation/v1/tx.proto (4)
54-54
: LGTM! The change torepeated KeyValue
is appropriate.Using
repeated KeyValue
instead of amap
ensures order consistency and avoids issues with deserialization in Golang.
59-62
: LGTM! The changes toMsgDelegation
are appropriate.The introduction of the
asset_id
field and reordering of fields enhance the clarity and functionality of the message.
113-114
: LGTM! The changes toMsgUndelegation
are appropriate.The introduction of the
asset_id
field and reordering of fields enhance the clarity and functionality of the message.
Line range hint
1-1
:
LGTM! The removal ofDelegationApproveInfo
is appropriate.The removal simplifies the delegation process and likely integrates its functionality elsewhere.
x/assets/keeper/staker_asset.go (1)
32-37
: Ensure error handling for native asset info retrieval.The added logic correctly retrieves native asset information. However, ensure that the error handling aligns with the overall error management strategy.
x/assets/keeper/staker_asset_test.go (1)
84-84
: Verify the new staker ID format.The staker ID format has been updated to use "0x0". Ensure this change aligns with the new requirements and verify its impact on subsequent logic.
x/slash/keeper/execute_slash.go (4)
47-56
: Ensure proper handling of action types.The action types have been updated to use
assetstypes
. Ensure all possible action types are handled correctly.
83-85
: Verify operator address handling.The operator address is now handled as
assetstypes.ExoCoreOperatorAddrLength
. Ensure this change is consistent with the new requirements.
105-105
: Verify cross-chain operation amount length.The cross-chain operation amount length is now handled as
assetstypes.CrossChainOpAmountLength
. Ensure this change is consistent with the new requirements.
189-208
: Clarify handling of native tokens in slashing logic.The logic for handling native tokens during slashing events is added. Ensure this logic is consistent with the overall strategy for native token management.
Verification successful
Clarify handling of native tokens in slashing logic.
The handling of native tokens in the slashing logic in
x/slash/keeper/execute_slash.go
is consistent with the overall strategy for native token management across the codebase. The pattern of checking forNativeAssetID
and applying specific logic is consistently followed.
x/slash/keeper/execute_slash.go
x/reward/keeper/claim_reward.go
x/delegation/keeper/msg_server.go
x/assets/keeper/staker_asset.go
Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify the handling of native tokens in slashing logic. # Test: Search for the usage of `NativeAssetID` in the slashing logic. rg --type go 'NativeAssetID' -A 5Length of output: 5310
Script:
#!/bin/bash # Description: Verify the handling of native tokens in slashing logic across the codebase. # Search for the usage of `NativeAssetID` in all Go files to understand the handling logic. rg --type go 'NativeAssetID' -A 10 -B 10Length of output: 15613
x/delegation/keeper/share.go (1)
216-217
: Verify consistency of the conditional check.Ensure that skipping the update of staker asset state for native tokens is consistent with other parts of the system.
Verification successful
Verified consistency of the conditional check.
The conditional check to skip updating the staker asset state for native tokens is consistent with other parts of the system.
x/slash/keeper/execute_slash.go
x/reward/keeper/claim_reward.go
x/delegation/keeper/msg_server.go
x/delegation/keeper/abci.go
x/delegation/keeper/cross_chain_tx_process.go
x/assets/keeper/staker_asset.go
x/assets/keeper/bank.go
Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Verify consistency of the conditional check for native tokens. # Test: Search for similar conditional checks in the codebase. Expect: Consistent handling of native tokens. rg --type python -A 5 $'NativeAssetID'Length of output: 68
Script:
#!/bin/bash # Description: Verify consistency of the conditional check for native tokens. # Test: Search for similar conditional checks in Go files. Expect: Consistent handling of native tokens. rg --type go -A 5 $'NativeAssetID'Length of output: 5310
// todo: TotalDepositAmount might be influenced by slash and precision loss, | ||
// consider removing it, it can be recalculated from the share for RPC query. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Address the TODO comment regarding TotalDepositAmount
.
The comment suggests potential issues with precision loss or other calculation inaccuracies. Consider addressing this in a future update.
Do you want me to open a GitHub issue to track this task?
a95751b
to
a1aed48
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 4
Outside diff range, codebase verification and nitpick comments (2)
x/assets/client/cli/tx.go (1)
Line range hint
45-46
: Validation step should not be removed.Removing the validation step for the
msg
object is concerning because it could allow invalid messages to be processed. Themsg.ValidateBasic()
check serves as an important safeguard to catch errors before the transaction is executed.Please retain the validation step:
msg := &assetstype.MsgUpdateParams{ Authority: sender.String(), Params: assetstype.Params{ ExocoreLzAppAddress: args[0], ExocoreLzAppEventTopic: args[1], }, } + if err := msg.ValidateBasic(); err != nil { + return err + } return tx.GenerateOrBroadcastTxCLI(cliCtx, cmd.Flags(), msg)x/assets/keeper/staker_asset.go (1)
42-76
: Approved with a suggestion for optimization.The code changes to handle the retrieval of native asset information for a staker are implemented correctly and align with the PR objectives. The error handling for address decoding has been improved as per the past review comment.
Suggestion: If the number of delegation records is expected to be large, consider optimizing the loop at line range 63-74 to improve performance. One approach could be to use goroutines to process the records concurrently.
Tools
GitHub Check: CodeQL
[warning] 63-74: Iteration over map
Iteration over map may be a possible source of non-determinism
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files ignored due to path filters (1)
x/delegation/types/tx.pb.go
is excluded by!**/*.pb.go
Files selected for processing (26)
- app/app.go (9 hunks)
- proto/exocore/delegation/v1/tx.proto (3 hunks)
- testutil/utils.go (1 hunks)
- x/assets/client/cli/tx.go (1 hunks)
- x/assets/keeper/bank.go (1 hunks)
- x/assets/keeper/expected_keepers.go (1 hunks)
- x/assets/keeper/keeper.go (1 hunks)
- x/assets/keeper/staker_asset.go (2 hunks)
- x/assets/keeper/staker_asset_test.go (1 hunks)
- x/assets/types/expected_keepers.go (1 hunks)
- x/assets/types/general.go (1 hunks)
- x/delegation/client/cli/tx.go (1 hunks)
- x/delegation/client/cli/tx_delegation_native.go (1 hunks)
- x/delegation/keeper/abci.go (4 hunks)
- x/delegation/keeper/delegation.go (1 hunks)
- x/delegation/keeper/delegation_op_test.go (7 hunks)
- x/delegation/keeper/delegation_state.go (1 hunks)
- x/delegation/keeper/keeper.go (4 hunks)
- x/delegation/keeper/msg_server.go (1 hunks)
- x/delegation/keeper/setup_test.go (2 hunks)
- x/delegation/keeper/share.go (1 hunks)
- x/delegation/keeper/un_delegation_state.go (1 hunks)
- x/delegation/types/cross_chain_params.go (1 hunks)
- x/delegation/types/expected_keepers.go (1 hunks)
- x/delegation/types/general.go (1 hunks)
- x/delegation/types/msg.go (2 hunks)
Files skipped from review due to trivial changes (2)
- testutil/utils.go
- x/delegation/keeper/un_delegation_state.go
Additional context used
Learnings (1)
x/delegation/keeper/msg_server.go (1)
Learnt from: MaxMustermann2 PR: ExocoreNetwork/exocore#127 File: x/delegation/keeper/msg_server.go:17-46 Timestamp: 2024-07-16T05:32:21.301Z Learning: The `msg` object in the `DelegateAssetToOperator` function is validated using `msg.ValidateBasic` before it reaches the function, ensuring that all addresses are correct and allowing the safe use of `sdk.MustAccAddressFromBech32`.
GitHub Check: CodeQL
x/delegation/keeper/abci.go
[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic call
[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt
[warning] 84-84: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic call
[warning] 84-84: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain haltx/assets/keeper/staker_asset.go
[warning] 63-74: Iteration over map
Iteration over map may be a possible source of non-determinism
GitHub Check: break-check
proto/exocore/delegation/v1/tx.proto
[failure] 54-54:
Field "2" on message "DelegationIncOrDecInfo" changed type from "exocore.delegation.v1.DelegationIncOrDecInfo.PerOperatorAmountsEntry" to "exocore.delegation.v1.KeyValue".
[failure] 60-60:
Field "1" with name "asset_id" on message "MsgDelegation" changed option "json_name" from "baseInfo" to "assetId".
[failure] 60-60:
Field "1" on message "MsgDelegation" changed type from "message" to "string".
[failure] 60-60:
Field "1" on message "MsgDelegation" changed name from "base_info" to "asset_id".
[failure] 62-62:
Field "2" with name "base_info" on message "MsgDelegation" changed option "json_name" from "approvedInfo" to "baseInfo".
[failure] 62-62:
Field "2" on message "MsgDelegation" changed type from "exocore.delegation.v1.DelegationApproveInfo" to "exocore.delegation.v1.DelegationIncOrDecInfo".
[failure] 62-62:
Field "2" on message "MsgDelegation" changed name from "approved_info" to "base_info".
[failure] 113-113:
Field "1" with name "asset_id" on message "MsgUndelegation" changed option "json_name" from "baseInfo" to "assetId".
Additional comments not posted (47)
x/assets/types/expected_keepers.go (1)
12-14
: LGTM!The new
BankKeeper
interface is well-defined and follows good practices:
- It abstracts the interaction with the bank module, promoting modularity.
- The
GetBalance
method signature is appropriate for retrieving the balance of an account for a specific denomination.The code changes are approved.
x/delegation/types/general.go (1)
5-10
: LGTM!The code changes are approved for the following reasons:
- The constants improve the clarity and organization of the code by providing semantic names for different types of token pools.
- The comment serves as a helpful reminder of the current limitations and the reasoning behind the naming of
DelegatedPoolName
.- The constants are declared correctly and follow the naming conventions.
x/assets/keeper/expected_keepers.go (1)
1-11
: LGTM!The code changes are approved.
The existing review comments discuss the placement of the interface definition and the reason for placing it in the
keeper
package. The comment added by the developer at line 8 addresses the concern raised in the previous review comments. Therefore, no further comments are necessary.x/delegation/client/cli/tx.go (1)
21-23
: LGTM!The code changes are approved for the following reasons:
- The
CmdDelegate
andCmdUndelegate
commands are correctly added to thetxCmd
command group.- The command names match their intended functionality, as described in the PR objectives and the AI-generated summary.
- The code changes are consistent with the PR objectives and the AI-generated summary.
x/delegation/keeper/setup_test.go (2)
8-8
: LGTM!The code changes are approved.
23-23
: LGTM!The code changes are approved.
x/delegation/types/cross_chain_params.go (1)
22-42
: LGTM!The constructor function
NewDelegationOrUndelegationParams
is correctly implemented and follows the best practices for constructor functions in Go. It takes several parameters that correspond to the fields of theDelegationOrUndelegationParams
struct and returns a pointer to a newly created instance of the struct. This function improves the usability of the struct by providing a clear and concise way to instantiate it, thereby enhancing code readability and maintainability.x/delegation/types/msg.go (2)
28-40
: LGTM!The code changes are approved.
67-79
: LGTM!The code changes are approved.
x/assets/keeper/bank.go (1)
50-63
: The existing comment on the changes is still valid:Conditional Logic for
exo-native-token
inPerformDepositOrWithdraw
The addition of a condition to skip updating staker info for
exo-native-token
is a significant change. This logic ensures that operations specific to the native token are handled differently, which is crucial given its unique role in the ecosystem.However, the
TODO
comment indicates uncertainty about whether additional processes are needed forexo-native-token
. It's important to address this to ensure that all necessary operations for the native token are correctly implemented.x/delegation/client/cli/tx_delegation_native.go (2)
16-39
: LGTM!The code changes are approved.
41-66
: LGTM!The code changes are approved.
x/delegation/keeper/keeper.go (4)
19-23
: LGTM!The addition of
accountKeeper
andbankKeeper
fields to theKeeper
struct enhances its capability to manage accounts and banking operations within the delegation module.
33-34
: LGTM!The updated
NewKeeper
function signature ensures that instances ofKeeper
can be initialized with the necessary dependencies for account and banking management.
42-43
: LGTM!The initialization of
accountKeeper
andbankKeeper
fields in theNewKeeper
function is consistent with the updatedKeeper
struct and function signature.
67-69
: LGTM!The new
Logger
method provides a context-aware logging interface that includes the module name, allowing for better tracking and debugging of operations related to the delegation module.x/assets/keeper/keeper.go (2)
16-17
: LGTM!The changes to the
Keeper
struct are approved. The addition of thebk
anddk
fields will allow theKeeper
to interact with the bank and delegation modules, respectively, to perform operations related to asset management and delegation. This is consistent with the PR summary.
24-25
: LGTM!The changes to the
NewKeeper
constructor function are approved. The addition of thebk
anddk
parameters and their use in initializing the corresponding fields of theKeeper
struct are necessary and consistent with the changes to theKeeper
struct.Also applies to: 31-32
x/delegation/types/expected_keepers.go (2)
57-61
: LGTM!The
BankKeeper
interface is well-defined and serves a clear purpose. The method names and parameters are self-explanatory, and the interface is correctly placed in thetypes
package.
63-65
: LGTM!The
AccountKeeper
interface is well-defined and serves a clear purpose. The method name and parameters are self-explanatory, and the interface is correctly placed in thetypes
package.x/delegation/keeper/abci.go (2)
72-86
: LGTM!The changes enhance the functionality of the undelegation process by introducing a new flow for handling native assets. If the
record.AssetID
matchesassetstypes.NativeAssetID
, it parses theStakerID
, retrieves the corresponding address, and undelegates coins directly to the account. If not matched, it falls back to the previous method of updating the staker's asset state usingassetstypes.DeltaStakerSingleAsset
. The changes look good.Tools
GitHub Check: CodeQL
[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic call
[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt
[warning] 84-84: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic call
[warning] 84-84: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt
76-76
: The previous review comments on panic warnings at line ranges 76-76 and 84-84 are still valid and applicable to the current code. Skipping generating similar comments.Also applies to: 84-84
Tools
GitHub Check: CodeQL
[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic call
[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain haltx/assets/types/general.go (4)
10-10
: The import path has been correctly updated based on the previous review comment.
16-18
: LGTM!The code changes are approved.
19-20
: LGTM!The code changes are approved. The modification to use
utils.BaseDenom
enhances the flexibility of the asset denomination.
21-23
: LGTM!The code changes are approved. The commented-out lines suggest a cleanup of unused constants.
proto/exocore/delegation/v1/tx.proto (4)
59-60
: LGTM: The addition of theasset_id
field is approved.The
asset_id
field has been added to theMsgDelegation
message as the first field, with a custom name specified for serialization. This addition enhances the clarity and specificity of the delegation operation by explicitly identifying the asset.Tools
GitHub Check: break-check
[failure] 60-60:
Field "1" with name "asset_id" on message "MsgDelegation" changed option "json_name" from "baseInfo" to "assetId".
[failure] 60-60:
Field "1" on message "MsgDelegation" changed type from "message" to "string".
[failure] 60-60:
Field "1" on message "MsgDelegation" changed name from "base_info" to "asset_id".
62-62
: No action required: The field order change is acceptable.The
base_info
field in theMsgDelegation
message has been moved to the second position. This change in the field order does not affect the functionality of the message.Tools
GitHub Check: break-check
[failure] 62-62:
Field "2" with name "base_info" on message "MsgDelegation" changed option "json_name" from "approvedInfo" to "baseInfo".
[failure] 62-62:
Field "2" on message "MsgDelegation" changed type from "exocore.delegation.v1.DelegationApproveInfo" to "exocore.delegation.v1.DelegationIncOrDecInfo".
[failure] 62-62:
Field "2" on message "MsgDelegation" changed name from "approved_info" to "base_info".
113-114
: LGTM: The addition of theasset_id
field is approved.The
asset_id
field has been added to theMsgUndelegation
message as the first field, with a custom name specified for serialization. This addition enhances the clarity and specificity of the undelegation operation by explicitly identifying the asset.No action required: The field order change is acceptable.
The
base_info
field in theMsgUndelegation
message has been moved to the second position. This change in the field order does not affect the functionality of the message.Tools
GitHub Check: break-check
[failure] 113-113:
Field "1" with name "asset_id" on message "MsgUndelegation" changed option "json_name" from "baseInfo" to "assetId".
54-54
: Verify the impact of the change from a map to a list structure.The
per_operator_amounts
field has been changed from amap<string, ValueField>
to arepeated KeyValue
. Ensure that this change does not break any existing code that relies on the previous map structure.Run the following script to verify the usage of the
per_operator_amounts
field:LGTM: The addition of the
gogoproto.nullable
option is approved.Setting the
gogoproto.nullable
option to false for theper_operator_amounts
field enforces stricter data integrity by indicating that this field cannot be null.Tools
GitHub Check: break-check
[failure] 54-54:
Field "2" on message "DelegationIncOrDecInfo" changed type from "exocore.delegation.v1.DelegationIncOrDecInfo.PerOperatorAmountsEntry" to "exocore.delegation.v1.KeyValue".x/assets/keeper/staker_asset.go (1)
32-37
: LGTM!The code changes to retrieve and add the native asset information for a staker are approved.
x/assets/keeper/staker_asset_test.go (1)
84-84
: Verify the reason for the change in thestakerID
format.The change alters the format of the
stakerID
variable by concatenatingsuite.Address
with "0x0" instead of "0". This suggests a shift in how staker IDs are represented.Please confirm the reason for this change and ensure that it aligns with the new standard or format for identifiers in the system. Also, verify that this change is consistently applied across the codebase.
x/delegation/keeper/msg_server.go (3)
17-72
: Approved: TheDelegateAssetToOperator
function has been updated to handle native token delegation.The changes to the
DelegateAssetToOperator
function align with the PR objectives and introduce several improvements:
- The function now checks if the asset being delegated is the native asset and returns an appropriate error if not, ensuring that only native tokens are supported.
- The use of the
newDelegationParams
helper function improves code readability and maintainability by encapsulating the logic for generating delegation parameters.- The error handling and logging statements provide better visibility into the delegation process, making it easier to identify and debug issues.
Overall, the changes enhance the functionality and maintainability of the delegation process.
74-104
: Approved: TheUndelegateAssetFromOperator
function has been updated to handle native token undelegation.The changes to the
UndelegateAssetFromOperator
function introduce several improvements:
- The function now checks if the asset being undelegated is the native asset and returns an appropriate error if not, ensuring that only native tokens are supported.
- The use of the
newDelegationParams
helper function improves code reusability and maintainability by leveraging the same logic for generating undelegation parameters as the delegation function.- The error handling ensures that any issues during the undelegation process are propagated appropriately.
These changes align with the PR objectives and enhance the functionality and maintainability of the undelegation process.
128-145
: Approved: ThenewDelegationParams
helper function improves code reusability and maintainability.The addition of the
newDelegationParams
helper function is a positive change that offers the following benefits:
- It encapsulates the logic for generating delegation or undelegation parameters, reducing code duplication and improving maintainability.
- It accepts the necessary base information and asset details as parameters, making it flexible and reusable across different scenarios.
- It returns a slice of
DelegationOrUndelegationParams
pointers, which aligns with the expected input for theDelegateTo
andUndelegateFrom
functions.The use of
sdk.MustAccAddressFromBech32
to convert the staker and operator addresses is safe based on the learnings from the previous review, as the input addresses are assumed to be valid at this point.Overall, the introduction of this helper function enhances the code quality and maintainability of the delegation and undelegation processes.
x/delegation/keeper/share.go (1)
224-233
: Conditional logic for handling native tokens.The introduction of conditional logic to skip updating staker asset state for native tokens is a critical change for differentiating the handling of these assets.
Please verify that skipping the update of staker asset state for native tokens is consistent with the behavior in other parts of the system.
x/delegation/keeper/delegation.go (2)
41-59
: LGTM!The code changes correctly handle the delegation logic for non-native assets by:
- Checking if the asset is non-native.
- Retrieving the staker's asset information.
- Verifying if the withdrawable amount is sufficient for delegation.
- Updating the staker's asset state if the delegation is valid.
The changes are approved.
60-64
: LGTM!The code segment correctly handles the delegation logic for native assets by:
- Creating a coin object representing the delegation amount.
- Transferring the delegation amount from the staker's account to the delegated pool.
The changes are approved.
x/delegation/keeper/delegation_state.go (1)
170-170
: LGTM!The code change enhances the clarity of the error handling by directly using the
Wrapf
method on the custom errordelegationtype.ErrNoKeyInTheStore
. This allows including the key that was not found in the store in the error message.x/delegation/keeper/delegation_op_test.go (4)
70-84
: LGTM!The code changes are approved.
145-187
: LGTM!The code changes are approved.
251-308
: LGTM!The code changes are approved.
Line range hint
312-451
: LGTM!The code changes are approved.
app/app.go (4)
119-120
: LGTM!The code changes are approved. The
vesting
andvestingtypes
imports are necessary for adding support for vesting accounts in the application.
260-260
: LGTM!The code change is approved. Adding the
vesting
module to theModuleBasics
variable is necessary for integrating the vesting functionality into the application.
292-294
: LGTM!The code changes are approved. Adding the module account permissions for the
exomint
,erc20
, anddelegation
modules is necessary for the proper functioning of these modules.
551-560
: LGTM!The code changes are approved. Updating the
AssetsKeeper
andDelegationKeeper
to take additional dependencies is necessary for their proper functioning within the application.
@@ -34,8 +38,8 @@ | |||
continue | |||
}*/ | |||
|
|||
recordID := delegationtype.GetUndelegationRecordKey(record.BlockNumber, record.LzTxNonce, record.TxHash, record.OperatorAddr) | |||
if k.GetUndelegationHoldCount(ctx, recordID) > 0 { | |||
recordID := types.GetUndelegationRecordKey(record.BlockNumber, record.LzTxNonce, record.TxHash, record.OperatorAddr) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Refactor: Consolidate types under a single namespace.
The change renames the imported delegationtype
to types
and uses types.GetUndelegationRecordKey
instead of delegationtype.GetUndelegationRecordKey
. This consolidates types under a single namespace without introducing any functional changes.
x/delegation/keeper/msg_server.go
Outdated
} | ||
} | ||
|
||
//--- |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
remove the commented code.
x/delegation/keeper/msg_server.go
Outdated
logger.Error("failed to get nonce", "error", err) | ||
return nil, err | ||
} | ||
// // stakerAddr := sdk.MustAccAddressFromBech32(msg.BaseInfo.FromAddress).Bytes() |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
remove the commented code.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
removed
Test object: a1aed48 |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 1
Outside diff range, codebase verification and nitpick comments (3)
x/delegation/client/cli/tx_delegation_native.go (2)
18-18
: Address the limitation mentioned in the TODO comment.The TODO comment indicates that the command currently only supports native tokens. Consider expanding the support to other token types in future iterations to enhance the functionality of the command.
70-70
: Improve the error message for the argument count check.- if len(args) != 3 { - return "", "", sdkmath.ZeroInt(), errors.New("3 arguments needed") + if len(args) != 3 { + return "", "", sdkmath.ZeroInt(), errors.New("exactly 3 arguments are required") }The error message should clearly indicate that exactly 3 arguments are required for the command.
x/assets/keeper/staker_asset.go (1)
42-76
: LGTM with a minor suggestion!The new
GetStakerSpecifiedAssetInfo
function looks good overall and aligns with the PR objective to handle native assets. A few observations:
- Consider adding more context to the error messages to improve debugging. For example:
- if err != nil { - return nil, err + if err != nil { + return nil, errorsmod.Wrap(err, "failed to parse stakerID") }
- The static analysis warning about iteration over map being a potential source of non-determinism is a false positive in this case. The order of iteration does not affect the correctness of the aggregated result.
Tools
GitHub Check: CodeQL
[warning] 63-74: Iteration over map
Iteration over map may be a possible source of non-determinism
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files selected for processing (7)
- proto/exocore/delegation/v1/tx.proto (3 hunks)
- x/assets/keeper/staker_asset.go (2 hunks)
- x/delegation/client/cli/tx_delegation_native.go (1 hunks)
- x/delegation/keeper/abci.go (4 hunks)
- x/delegation/keeper/msg_server.go (1 hunks)
- x/delegation/types/errors.go (1 hunks)
- x/delegation/types/msg.go (3 hunks)
Additional context used
GitHub Check: CodeQL
x/delegation/keeper/abci.go
[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt
[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic call
[warning] 84-84: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt
[warning] 84-84: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic callx/assets/keeper/staker_asset.go
[warning] 63-74: Iteration over map
Iteration over map may be a possible source of non-determinism
GitHub Check: break-check
proto/exocore/delegation/v1/tx.proto
[failure] 54-54:
Field "2" on message "DelegationIncOrDecInfo" changed type from "exocore.delegation.v1.DelegationIncOrDecInfo.PerOperatorAmountsEntry" to "exocore.delegation.v1.KeyValue".
[failure] 60-60:
Field "1" with name "asset_id" on message "MsgDelegation" changed option "json_name" from "baseInfo" to "assetId".
[failure] 60-60:
Field "1" on message "MsgDelegation" changed type from "message" to "string".
[failure] 60-60:
Field "1" on message "MsgDelegation" changed name from "base_info" to "asset_id".
[failure] 62-62:
Field "2" with name "base_info" on message "MsgDelegation" changed option "json_name" from "approvedInfo" to "baseInfo".
[failure] 62-62:
Field "2" on message "MsgDelegation" changed type from "exocore.delegation.v1.DelegationApproveInfo" to "exocore.delegation.v1.DelegationIncOrDecInfo".
[failure] 62-62:
Field "2" on message "MsgDelegation" changed name from "approved_info" to "base_info".
[failure] 113-113:
Field "1" with name "asset_id" on message "MsgUndelegation" changed option "json_name" from "baseInfo" to "assetId".
Additional comments not posted (17)
x/delegation/types/errors.go (1)
82-85
: LGTM!The addition of
ErrInvalidAssetID
enhances the error handling capabilities of the module by allowing it to explicitly signal when an invalid asset ID is encountered, thereby improving the clarity and specificity of error reporting in the codebase.x/delegation/types/msg.go (5)
22-23
: LGTM!The refactoring of the
ValidateBasic
method forMsgDelegation
to utilize the new helper functionvalidateDelegationInfo
enhances code reusability and maintainability by reducing redundancy.
53-53
: LGTM!The refactoring of the
ValidateBasic
method forMsgUndelegation
to utilize the new helper functionvalidateDelegationInfo
enhances code reusability and maintainability by reducing redundancy.
26-36
: LGTM!The addition of the
NewMsgDelegation
function encapsulates the delegation process within this constructor, improving clarity and ensuring that theMsgDelegation
instance is properly initialized.
62-74
: LGTM!The addition of the
NewMsgUndelegation
function encapsulates the undelegation process within this constructor, improving clarity and ensuring that theMsgUndelegation
instance is properly initialized.
77-93
: LGTM!The implementation of the
validateDelegationInfo
function performs comprehensive checks on the asset ID and the operator addresses, enforcing stricter validation and replacing the previous inline validation logic. This streamlines the validation process and improves the overall robustness of the delegation and undelegation processes.x/delegation/keeper/abci.go (3)
41-41
: Refactor: Consolidate types under a single namespace.The change renames the imported
delegationtype
totypes
and usestypes.GetUndelegationRecordKey
instead ofdelegationtype.GetUndelegationRecordKey
. This consolidates types under a single namespace without introducing any functional changes.
62-64
: Refactor: Consolidate types under a single namespace.The change updates the handling of the
deltaAmount
structure to usetypes.DeltaDelegationAmounts
instead ofdelegationtype.DeltaDelegationAmounts
. This is consistent with the overall renaming and suggests a consolidation of types under a single namespace without introducing any functional changes.
89-89
: Refactor: Ensure consistency across asset state updates.The change updates the error handling for updating the operator state to utilize
assetstypes.DeltaOperatorSingleAsset
, ensuring consistency across the asset state updates.x/delegation/keeper/msg_server.go (3)
17-49
: Enhance asset delegation logic and control flow.The
DelegateAssetToOperator
method has been redefined to include comprehensive logic for handling asset delegation. It checks if the asset being delegated is the native asset, logging errors and returning appropriate responses if it is not. The method retrieves the account nonce and computes a unique hash for the transaction, which is used in the delegation process. It utilizes thenewDelegationParams
helper function to construct a list of delegation parameters.These changes significantly improve the logic and control flow of asset delegation within the Keeper, allowing for more robust handling of the delegation process. The use of the
newDelegationParams
helper function enhances code clarity and reusability.
51-78
: AddUndelegateAssetFromOperator
method for enhanced asset undelegation functionality.A new method,
UndelegateAssetFromOperator
, has been added, mirroring the structure of the delegation method. It checks for the native asset, retrieves the nonce, and computes a unique hash before proceeding with the undelegation logic. It utilizes thenewDelegationParams
helper function to construct a list of undelegation parameters.The addition of this method enhances the functionality for asset undelegation, following a similar structure to the delegation method. The use of the
newDelegationParams
helper function ensures consistency and reusability across both methods.
81-98
: IntroducenewDelegationParams
helper function for improved code modularity and reusability.A new helper function,
newDelegationParams
, has been added to construct a list of delegation parameters based on the provided base information and asset details. It consolidates the logic for creating delegation parameters, which is used in both the delegation and undelegation methods.The introduction of this helper function enhances code modularity and reusability by consolidating the logic for creating delegation parameters. This approach improves code clarity and maintainability.
proto/exocore/delegation/v1/tx.proto (2)
54-54
: Breaking change: Modifyper_operator_amounts
field inDelegationIncOrDecInfo
message.The
per_operator_amounts
field in theDelegationIncOrDecInfo
message has been changed from amap<string, ValueField>
to arepeated KeyValue
. This change alters how amounts are represented and may affect how data is serialized and deserialized, suggesting a more structured approach to handling multiple operator amounts, possibly enhancing clarity and usability.However, as indicated by the static analysis tool, this change breaks compatibility with the previous version of the protocol.
Please verify the impact of this change on existing clients and data, and ensure that any necessary migration steps are documented and communicated to users. Consider the following:
- How will existing data be migrated to the new format?
- Will existing clients need to be updated to handle the new format?
- Are there any potential data loss or corruption risks during the migration process?
- How will the change be communicated to users and developers?
Tools
GitHub Check: break-check
[failure] 54-54:
Field "2" on message "DelegationIncOrDecInfo" changed type from "exocore.delegation.v1.DelegationIncOrDecInfo.PerOperatorAmountsEntry" to "exocore.delegation.v1.KeyValue".
59-60
: Breaking change: Introduceasset_id
field inMsgDelegation
message.A new
asset_id
field has been introduced at position 1 in theMsgDelegation
message. This change emphasizes the importance of the asset ID in delegation operations, potentially impacting how these messages are processed in the system.However, as indicated by the static analysis tool, this change breaks compatibility with the previous version of the protocol due to the change in field order and type.
Please verify the impact of this change on existing clients and message processing, and ensure that any necessary updates are made to maintain compatibility. Consider the following:
- Will existing clients need to be updated to include the
asset_id
field when constructingMsgDelegation
messages?- How will the system handle
MsgDelegation
messages that do not include theasset_id
field?- Are there any potential risks or unintended consequences of changing the field order and type?
- How will the change be communicated to users and developers?
Tools
GitHub Check: break-check
[failure] 60-60:
Field "1" with name "asset_id" on message "MsgDelegation" changed option "json_name" from "baseInfo" to "assetId".
[failure] 60-60:
Field "1" on message "MsgDelegation" changed type from "message" to "string".
[failure] 60-60:
Field "1" on message "MsgDelegation" changed name from "base_info" to "asset_id".x/assets/keeper/staker_asset.go (3)
7-8
: LGTM!The new imports are necessary for the added functionality.
32-37
: LGTM!The new logic to retrieve native asset information for the staker aligns with the PR objective and the error handling looks good.
Line range hint
92-125
:
x/delegation/keeper/abci.go
Outdated
if record.AssetID == assetstypes.NativeAssetID { | ||
parsedStakerID := strings.Split(record.StakerID, "_") | ||
stakerAddr := sdk.AccAddress(hexutil.MustDecode(parsedStakerID[0])) | ||
if err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, types.DelegatedPoolName, stakerAddr, sdk.NewCoins(sdk.NewCoin(assetstypes.NativeAssetDenom, record.ActualCompletedAmount))); err != nil { | ||
panic(err) | ||
} | ||
} else { | ||
err = k.assetsKeeper.UpdateStakerAssetState(ctx, record.StakerID, record.AssetID, assetstypes.DeltaStakerSingleAsset{ | ||
WithdrawableAmount: record.ActualCompletedAmount, | ||
WaitUnbondingAmount: recordAmountNeg, | ||
}) | ||
if err != nil { | ||
panic(err) | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Enhance clarity and performance for native asset undelegation, but avoid using panic
for error handling.
The change introduces a new control flow that handles the undelegation of native assets differently from other assets. If the asset ID matches assetstypes.NativeAssetID
, the code now parses the staker ID and directly undelegates coins from the module to the account, bypassing the previous method of updating the staker asset state for native assets. This enhances clarity and potentially improves performance.
However, the use of panic
for error handling in lines 76 and 84 could cause a chain halt, as indicated by the static analysis tool.
Replace the panic
calls with proper error handling:
- if err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, types.DelegatedPoolName, stakerAddr, sdk.NewCoins(sdk.NewCoin(assetstypes.NativeAssetDenom, record.ActualCompletedAmount))); err != nil {
- panic(err)
- }
+ err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, types.DelegatedPoolName, stakerAddr, sdk.NewCoins(sdk.NewCoin(assetstypes.NativeAssetDenom, record.ActualCompletedAmount)))
+ if err != nil {
+ return nil, err
+ }
- if err != nil {
- panic(err)
- }
+ if err != nil {
+ return nil, err
+ }
Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
if record.AssetID == assetstypes.NativeAssetID { | |
parsedStakerID := strings.Split(record.StakerID, "_") | |
stakerAddr := sdk.AccAddress(hexutil.MustDecode(parsedStakerID[0])) | |
if err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, types.DelegatedPoolName, stakerAddr, sdk.NewCoins(sdk.NewCoin(assetstypes.NativeAssetDenom, record.ActualCompletedAmount))); err != nil { | |
panic(err) | |
} | |
} else { | |
err = k.assetsKeeper.UpdateStakerAssetState(ctx, record.StakerID, record.AssetID, assetstypes.DeltaStakerSingleAsset{ | |
WithdrawableAmount: record.ActualCompletedAmount, | |
WaitUnbondingAmount: recordAmountNeg, | |
}) | |
if err != nil { | |
panic(err) | |
} | |
if record.AssetID == assetstypes.NativeAssetID { | |
parsedStakerID := strings.Split(record.StakerID, "_") | |
stakerAddr := sdk.AccAddress(hexutil.MustDecode(parsedStakerID[0])) | |
err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, types.DelegatedPoolName, stakerAddr, sdk.NewCoins(sdk.NewCoin(assetstypes.NativeAssetDenom, record.ActualCompletedAmount))) | |
if err != nil { | |
return nil, err | |
} | |
} else { | |
err = k.assetsKeeper.UpdateStakerAssetState(ctx, record.StakerID, record.AssetID, assetstypes.DeltaStakerSingleAsset{ | |
WithdrawableAmount: record.ActualCompletedAmount, | |
WaitUnbondingAmount: recordAmountNeg, | |
}) | |
if err != nil { | |
return nil, err | |
} | |
} |
Tools
GitHub Check: CodeQL
[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt
[warning] 76-76: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic call
[warning] 84-84: Panic in BeginBock or EndBlock consensus methods
Possible panics in BeginBock- or EndBlock-related consensus methods could cause a chain halt
[warning] 84-84: Panic in BeginBock or EndBlock consensus methods
path flow from Begin/EndBlock to a panic call
With this PR native |
@leonz789 good to merge. |
f34bb2c
to
651715a
Compare
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Actionable comments posted: 14
Outside diff range and nitpick comments (7)
x/delegation/types/general.go (1)
5-10
: LGTM! The new constants improve code clarity and maintainability.The introduction of the
NotBondedPoolName
,BondedPoolName
, andDelegatedPoolName
constants in thetypes
package is a great addition. It provides a centralized and standardized way to refer to the different token pools across the delegation module, reducing the risk of inconsistencies and making the code more maintainable.The constant names are clear, descriptive, and follow the naming convention of appending "PoolName" to each constant, which enhances code readability.
The TODO comment provides valuable context for the use of
DelegatedPoolName
, indicating that it's a temporary solution until redelegation and operator bonding are fully implemented. This comment serves as a reminder for future enhancements and ensures that the current limitations are clearly communicated to other developers.To address the TODO comment, consider creating a new GitHub issue to track the implementation of redelegation and operator bonding. This will ensure that the task is properly prioritized and not overlooked in the future. Let me know if you'd like me to assist in creating the issue.
x/delegation/client/cli/tx_delegation_native.go (1)
43-43
: Address the limitation mentioned in the TODO comment.Similar to the
CmdDelegate
function, the TODO comment indicates that the command currently only supports native tokens. Consider expanding the support to other token types in future iterations to enhance the functionality of the command.x/delegation/keeper/share.go (1)
226-227
: Address the TODO comment.The comment suggests potential issues with precision loss or other inaccuracies in the calculation of
TotalDepositAmount
. It's important to investigate and address this concern to ensure accurate financial calculations.Do you want me to open a GitHub issue to track this task?
x/delegation/keeper/keeper.go (2)
67-69
: Add Comment for Exported MethodLogger
The method
Logger
is exported but lacks a comment. It's best practice in Go to document exported methods to enhance code readability and maintainability.Apply this diff to add a comment:
+// Logger returns a module-specific logger. func (k Keeper) Logger(ctx sdk.Context) log.Logger { return ctx.Logger().With("module", fmt.Sprintf("x/%s", delegationtype.ModuleName)) }
67-69
: Consider Using Pointer Receiver for ConsistencyThe
Logger
method uses a value receiver(k Keeper)
, whereas other methods likeSetHooks
use a pointer receiver(k *Keeper)
. For consistency across the codebase, consider using a pointer receiver for theLogger
method.Apply this diff to change the receiver type:
-func (k Keeper) Logger(ctx sdk.Context) log.Logger { +func (k *Keeper) Logger(ctx sdk.Context) log.Logger { return ctx.Logger().With("module", fmt.Sprintf("x/%s", delegationtype.ModuleName)) }x/delegation/types/msg.go (1)
76-76
: Consider unifyingMsgDelegation
andMsgUndelegation
Since both messages share the same parameters, consolidating them into a single message with an action flag (e.g.,
IsDelegation bool
) could reduce redundancy and simplify the API.x/delegation/keeper/delegation_op_test.go (1)
Line range hint
312-451
: Extract epoch advancement logic into a helper functionThe loops advancing epochs are repeated for both asset types in
TestCompleteUndelegation
. Refactoring this logic into a helper function will reduce code duplication and improve readability.Apply this refactor:
+func (suite *DelegationTestSuite) advanceEpochs(epochsUntilUnbonded int64) { + epochID := suite.App.StakingKeeper.GetEpochIdentifier(suite.Ctx) + epochInfo, _ := suite.App.EpochsKeeper.GetEpochInfo(suite.Ctx, epochID) + for i := 0; i < int(epochsUntilUnbonded); i++ { + epochEndTime := epochInfo.CurrentEpochStartTime.Add(epochInfo.Duration) + suite.Ctx = suite.Ctx.WithBlockTime(epochEndTime.Add(1 * time.Second)) + suite.App.EpochsKeeper.BeginBlocker(suite.Ctx) + epochInfo, _ = suite.App.EpochsKeeper.GetEpochInfo(suite.Ctx, epochID) + } +} func (suite *DelegationTestSuite) TestCompleteUndelegation() { // existing code... - for i := 0; i < int(epochsUntilUnbonded); i++ { - epochEndTime := epochInfo.CurrentEpochStartTime.Add(epochInfo.Duration) - suite.Ctx = suite.Ctx.WithBlockTime(epochEndTime.Add(1 * time.Second)) - suite.App.EpochsKeeper.BeginBlocker(suite.Ctx) - epochInfo, _ = suite.App.EpochsKeeper.GetEpochInfo(suite.Ctx, epochID) - } + suite.advanceEpochs(epochsUntilUnbonded) // existing code... - for i := 0; i < int(epochsUntilUnbonded); i++ { - epochEndTime := epochInfo.CurrentEpochStartTime.Add(epochInfo.Duration) - suite.Ctx = suite.Ctx.WithBlockTime(epochEndTime.Add(1 * time.Second)) - suite.App.EpochsKeeper.BeginBlocker(suite.Ctx) - epochInfo, _ = suite.App.EpochsKeeper.GetEpochInfo(suite.Ctx, epochID) - } + suite.advanceEpochs(epochsUntilUnbonded) }
Review details
Configuration used: CodeRabbit UI
Review profile: CHILL
Files ignored due to path filters (1)
x/delegation/types/tx.pb.go
is excluded by!**/*.pb.go
Files selected for processing (29)
- app/app.go (9 hunks)
- proto/exocore/delegation/v1/tx.proto (2 hunks)
- testutil/utils.go (0 hunks)
- x/assets/client/cli/tx.go (0 hunks)
- x/assets/keeper/bank.go (1 hunks)
- x/assets/keeper/expected_keepers.go (1 hunks)
- x/assets/keeper/keeper.go (1 hunks)
- x/assets/keeper/staker_asset.go (2 hunks)
- x/assets/keeper/staker_asset_test.go (1 hunks)
- x/assets/types/expected_keepers.go (1 hunks)
- x/assets/types/general.go (1 hunks)
- x/delegation/client/cli/tx.go (1 hunks)
- x/delegation/client/cli/tx_delegation_native.go (1 hunks)
- x/delegation/keeper/abci.go (4 hunks)
- x/delegation/keeper/delegation.go (1 hunks)
- x/delegation/keeper/delegation_op_test.go (7 hunks)
- x/delegation/keeper/delegation_state.go (1 hunks)
- x/delegation/keeper/keeper.go (4 hunks)
- x/delegation/keeper/msg_server.go (1 hunks)
- x/delegation/keeper/setup_test.go (2 hunks)
- x/delegation/keeper/share.go (1 hunks)
- x/delegation/types/cross_chain_params.go (1 hunks)
- x/delegation/types/errors.go (1 hunks)
- x/delegation/types/expected_keepers.go (1 hunks)
- x/delegation/types/general.go (1 hunks)
- x/delegation/types/msg.go (3 hunks)
- x/oracle/keeper/prices.go (3 hunks)
- x/reward/keeper/claim_reward.go (1 hunks)
- x/slash/keeper/execute_slash.go (6 hunks)
Files not reviewed due to no reviewable changes (2)
- testutil/utils.go
- x/assets/client/cli/tx.go
Additional context used
GitHub Check: break-check
proto/exocore/delegation/v1/tx.proto
[failure] 54-54:
Field "2" on message "DelegationIncOrDecInfo" changed type from "exocore.delegation.v1.DelegationIncOrDecInfo.PerOperatorAmountsEntry" to "exocore.delegation.v1.KeyValue".
[failure] 60-60:
Field "1" with name "asset_id" on message "MsgDelegation" changed option "json_name" from "baseInfo" to "assetId".
[failure] 60-60:
Field "1" on message "MsgDelegation" changed type from "message" to "string".
[failure] 60-60:
Field "1" on message "MsgDelegation" changed name from "base_info" to "asset_id".
[failure] 62-62:
Field "2" with name "base_info" on message "MsgDelegation" changed option "json_name" from "approvedInfo" to "baseInfo".
[failure] 62-62:
Field "2" on message "MsgDelegation" changed type from "exocore.delegation.v1.DelegationApproveInfo" to "exocore.delegation.v1.DelegationIncOrDecInfo".
[failure] 62-62:
Field "2" on message "MsgDelegation" changed name from "approved_info" to "base_info".
[failure] 113-113:
Field "1" with name "asset_id" on message "MsgUndelegation" changed option "json_name" from "baseInfo" to "assetId".
Additional comments not posted (49)
x/assets/keeper/expected_keepers.go (1)
1-11
: The past review comments discussing the placement of thedelegationKeeper
interface definition and the reasoning behind it are still valid. The comment explaining the reason for placing the interface definition in thekeeper
package to avoid a circular dependency has been added as suggested. No further action is required.x/assets/types/expected_keepers.go (1)
12-15
: LGTM!The addition of the
BankKeeper
interface aligns with the PR objective of managing native token asset information through the bank module. TheGetBalance
method will enable querying account balances for delegation and undelegation operations within theassets
module.x/delegation/client/cli/tx.go (1)
21-23
: LGTM!The addition of the
CmdDelegate()
andCmdUndelegate()
commands to thetxCmd
command set is a valuable enhancement that aligns with the PR objectives. The function names are consistent with the intended functionality, and the changes are well-integrated into the existing command structure.x/delegation/keeper/setup_test.go (2)
8-8
: LGTM!The import statement for the
sdk
package fromgithub.com/cosmos/cosmos-sdk/types
is valid and follows the correct syntax. It is a commonly used Cosmos SDK package for handling types and is likely added to support the usage ofsdk.AccAddress
type in the test suite.
23-23
: LGTM!The addition of the
accAddr
field of typesdk.AccAddress
to theDelegationTestSuite
struct is valid and follows the correct syntax. Thesdk.AccAddress
type is a commonly used Cosmos SDK type for representing account addresses. The field is likely added to store an account address that will be used in the test cases.x/delegation/types/cross_chain_params.go (1)
22-42
: LGTM!The addition of the
NewDelegationOrUndelegationParams
constructor function is a good practice. It enhances the usability of theDelegationOrUndelegationParams
struct by providing a clear method for instantiation and ensures that all fields are properly initialized when creating a new instance of the struct.The function takes the necessary parameters and initializes the struct fields correctly. The logic and syntax are accurate.
x/assets/keeper/bank.go (1)
43-56
: Address the TODO comment to ensure correct handling of the native token.The past review comment is still valid and applicable:
The addition of a condition to skip updating staker info for
exo-native-token
is a significant change. This logic ensures that operations specific to the native token are handled differently, which is crucial given its unique role in the ecosystem.However, the
TODO
comment indicates uncertainty about whether additional processes are needed forexo-native-token
. It's important to address this to ensure that all necessary operations for the native token are correctly implemented.Please ensure that you have thoroughly considered and implemented all necessary operations for the native token. Skipping updates for the native token without proper handling could lead to inconsistencies in the asset state and total amount.
To verify the correct handling of the native token, run the following script:
#!/bin/bash # Description: Verify that all necessary operations for the native token are implemented correctly. # Test 1: Search for any additional processes specific to the native token. rg --type go -A 5 $'assetstypes\.NativeAssetID' # Test 2: Search for any inconsistencies in the asset state and total amount for the native token. ast-grep --lang go --pattern $'if $$$; err != nil { return errorsmod.Wrapf(err, $$$) }'If the script output reveals any missing operations or inconsistencies, please address them to ensure the correct handling of the native token.
x/delegation/types/errors.go (1)
82-85
: LGTM!The new error variable
ErrInvalidAssetID
is declared and registered correctly, following the existing pattern in the file. The error code 18 is unique and follows the sequence of the existing error codes. The error message clearly conveys the purpose of the error, indicating that the asset ID is invalid.This addition will help in identifying and handling cases where an invalid asset ID is encountered in the delegation module, improving error handling and providing a specific error message for such scenarios.
x/delegation/client/cli/tx_delegation_native.go (2)
18-18
: ****
Address the limitation mentioned in the TODO comment.The TODO comment indicates that the command currently only supports native tokens. Consider expanding the support to other token types in future iterations to enhance the functionality of the command.
68-82
: ****
Improve the input validation inparseArgs
.Please apply the following changes suggested in the previous review comment:
- if len(args) != 3 { - return "", "", sdkmath.ZeroInt(), errors.New("3 arguments needed") - } + if len(args) != 3 { + return "", "", sdkmath.ZeroInt(), errors.New("exactly 3 arguments are required") + } assetID := args[0] operatorAddrStr := args[1] amount, ok := sdkmath.NewIntFromString(args[2]) if !ok || amount.LTE(sdkmath.ZeroInt()) { return "", "", sdkmath.ZeroInt(), errors.New("amount invalid") } return assetID, operatorAddrStr, amount, nilx/assets/keeper/keeper.go (2)
16-17
: LGTM!The addition of the
bk
anddk
fields to theKeeper
struct is a necessary step to enable the assets module to interact with the bank and delegation modules. This change aligns with the PR objective of integrating delegation functionality for native tokens.
24-25
: Looks good!The updates to the
NewKeeper
constructor are necessary to initialize the newly addedbk
anddk
fields in theKeeper
struct. These changes maintain consistency with the struct modifications and ensure that the assets module has access to the required dependencies from the bank and delegation modules.Also applies to: 31-32
x/delegation/types/expected_keepers.go (2)
57-61
: LGTM!The
BankKeeper
interface provides a clean abstraction for managing coin balances and delegation/undelegation flows between accounts and modules. The method signatures are well-defined and serve their intended purpose.
63-65
: LGTM!The
AccountKeeper
interface provides a clear abstraction for account-related operations. TheGetSequence
method is essential for retrieving the account sequence number, which plays a vital role in transaction ordering and preventing replay attacks.x/delegation/keeper/msg_server.go (3)
17-49
: LGTM!The
DelegateAssetToOperator
function implements the core logic for delegating assets to an operator. Here are the key aspects of the function:
- It checks if the asset being delegated is the native asset and returns an error if not. This ensures that only supported assets are delegated.
- It retrieves the nonce for the sender's address and computes a unique hash based on the transaction bytes and nonce. This helps in generating a unique identifier for each delegation transaction.
- It creates delegation parameters using the
newDelegationParams
helper function, which makes the code more modular and reusable.- It attempts to delegate the asset using the generated delegation parameters and logs any errors encountered during the process.
The function is well-structured and follows good practices such as error handling and logging.
51-78
: LGTM!The
UndelegateAssetFromOperator
function implements the core logic for undelegating assets from an operator. Here are the key aspects of the function:
- It checks if the asset being undelegated is the native asset and returns an error if not. This ensures that only supported assets are undelegated.
- It retrieves the nonce for the sender's address and computes a unique hash based on the transaction bytes and nonce. This helps in generating a unique identifier for each undelegation transaction.
- It creates undelegation parameters using the
newDelegationParams
helper function, which is reused from the delegation logic. This promotes code reusability and maintainability.- It attempts to undelegate the asset using the generated undelegation parameters and returns any error encountered during the process.
The function follows a similar structure to the
DelegateAssetToOperator
function and adheres to good practices such as error handling and code reuse.
81-98
: LGTM!The
newDelegationParams
function is a helper function that generates a list of delegation or undelegation parameters based on the provided base information and other necessary details. Here are the key aspects of the function:
- It takes the base info, asset address, client chain ID, nonce, and transaction hash as parameters.
- It creates a slice of
DelegationOrUndelegationParams
with a capacity of 1 to store the generated parameters.- It iterates over the
PerOperatorAmounts
map in the base information and creates aDelegationOrUndelegationParams
object for each entry using theNewDelegationOrUndelegationParams
function.- It appends each
DelegationOrUndelegationParams
object to the result slice and returns the slice.The function encapsulates the logic for creating
DelegationOrUndelegationParams
objects, making the code more modular and reusable. It is used by both theDelegateAssetToOperator
andUndelegateAssetFromOperator
functions, promoting code reuse and maintainability.x/assets/types/general.go (1)
16-21
: LGTM!The new constant block is well-defined and provides a clear, centralized definition for the native asset and chain properties. The use of
utils.BaseDenom
forNativeAssetDenom
aligns with the suggestion from the previous review comment.proto/exocore/delegation/v1/tx.proto (5)
54-54
: Approve the change from map to repeated KeyValue forper_operator_amounts
.The change from using a map to a repeated
KeyValue
type for theper_operator_amounts
field is a good solution to ensure a consistent order of the data. As mentioned in the comment, the order of insertion in a map affects the state root in Cosmos, and deserializing a protobuf map into Golang does not guarantee order. Using a repeated field of key-value pairs instead of a map mitigates this issue.Setting
gogoproto.nullable
to false for this field is also a good practice to ensure that it cannot be left unset.Note that this change will require corresponding updates in the code that uses this message to handle the new structure.
Tools
GitHub Check: break-check
[failure] 54-54:
Field "2" on message "DelegationIncOrDecInfo" changed type from "exocore.delegation.v1.DelegationIncOrDecInfo.PerOperatorAmountsEntry" to "exocore.delegation.v1.KeyValue".
59-60
: Approve the addition of theasset_id
field toMsgDelegation
.Adding the
asset_id
field to theMsgDelegation
message at position 1 is a good change that allows specifying the identity of the asset being delegated. Using thegogoproto.customname
option with "AssetID" ensures that the field follows the Go naming convention in the generated code.Please note that this is a breaking change for the
MsgDelegation
message, as it adds a new required field. Any code that creates or handlesMsgDelegation
messages will need to be updated to provide theasset_id
.Tools
GitHub Check: break-check
[failure] 60-60:
Field "1" with name "asset_id" on message "MsgDelegation" changed option "json_name" from "baseInfo" to "assetId".
[failure] 60-60:
Field "1" on message "MsgDelegation" changed type from "message" to "string".
[failure] 60-60:
Field "1" on message "MsgDelegation" changed name from "base_info" to "asset_id".
62-62
: Approve the change in the field order forMsgDelegation
.Moving the
base_info
field to position 2 in theMsgDelegation
message is a necessary change to maintain the correct field order after adding the newasset_id
field at position 1.Please note that this is a breaking change for the
MsgDelegation
message. Any code that creates or handlesMsgDelegation
messages will need to be updated to use the new field order.Tools
GitHub Check: break-check
[failure] 62-62:
Field "2" with name "base_info" on message "MsgDelegation" changed option "json_name" from "approvedInfo" to "baseInfo".
[failure] 62-62:
Field "2" on message "MsgDelegation" changed type from "exocore.delegation.v1.DelegationApproveInfo" to "exocore.delegation.v1.DelegationIncOrDecInfo".
[failure] 62-62:
Field "2" on message "MsgDelegation" changed name from "approved_info" to "base_info".
112-113
: Approve the addition of theasset_id
field toMsgUndelegation
.Adding the
asset_id
field to theMsgUndelegation
message at position 1 is a good change that allows specifying the identity of the asset being undelegated. Using thegogoproto.customname
option with "AssetID" ensures that the field follows the Go naming convention in the generated code.Please note that this is a breaking change for the
MsgUndelegation
message, as it adds a new required field. Any code that creates or handlesMsgUndelegation
messages will need to be updated to provide theasset_id
.Tools
GitHub Check: break-check
[failure] 113-113:
Field "1" with name "asset_id" on message "MsgUndelegation" changed option "json_name" from "baseInfo" to "assetId".
115-115
: Approve the change in the field order forMsgUndelegation
.Moving the
base_info
field to position 2 in theMsgUndelegation
message is a necessary change to maintain the correct field order after adding the newasset_id
field at position 1.Please note that this is a breaking change for the
MsgUndelegation
message. Any code that creates or handlesMsgUndelegation
messages will need to be updated to use the new field order.x/assets/keeper/staker_asset_test.go (1)
84-84
: LGTM!The change to the
stakerID
format is a minor update that doesn't affect the correctness of the test. It might be for consistency with howstakerID
is represented in other parts of the codebase.x/slash/keeper/execute_slash.go (4)
27-27
: LGTM!The
Action
field type update aligns with the import alias change.
Line range hint
47-105
: LGTM!The updates to variable types and references in the
getParamsFromEventLog
function align with the import alias change fromtypes
toassetstypes
. The changes are consistent and do not introduce any apparent issues.
194-195
: Clarify the comment about additional processes for native tokens.The comment on line 195 asks whether additional processes are needed for native tokens. This requires clarification to ensure that the special handling of native tokens is properly implemented and does not introduce any unintended consequences.
196-208
: Verify the impact of skipping asset state updates for native tokens.The conditional block for updating staker asset state and staking asset total amount has been updated to skip these updates for native tokens. It's crucial to ensure that this change does not lead to inconsistencies in the system's state management.
Please verify that skipping these updates for native tokens is the intended behavior and does not introduce any issues or discrepancies in the overall asset management logic.
x/oracle/keeper/prices.go (2)
50-57
: LGTM!The added conditional check correctly handles the special case for the native asset identified by
assetstypes.NativeAssetID
. Returning a default price for the native asset using predefined constants is a necessary and maintainable approach.
103-110
: Looks good!The added conditional check correctly handles the special case for the native asset identified by
assetstypes.NativeAssetID
within the loop. Assigning a default price to theprices
map for the native asset and using thecontinue
statement to move to the next asset is a clean and maintainable approach.x/delegation/keeper/delegation_state.go (1)
197-197
: Improved error handling using a custom error type.The change from using
errorsmod.Wrap
todelegationtype.ErrNoKeyInTheStore.Wrapf
enhances the error handling in theGetSingleDelegationInfo
method. By utilizing a custom error type specific to the delegation package, the code provides more context about the error scenario. TheWrapf
method also allows for formatting the error message with additional details, making it more informative.This change improves the overall error handling without introducing any new bugs or logic errors. The modification is localized and does not affect other parts of the codebase.
x/delegation/keeper/keeper.go (2)
19-23
: New Keeper Dependencies Added CorrectlyThe
accountKeeper
andbankKeeper
have been appropriately added to theKeeper
struct. This integration aligns with the requirements for managing native token delegation and undelegation.
33-34
: Verify Initialization of New Keeper DependenciesThe
NewKeeper
constructor now includesaccountKeeper
andbankKeeper
. Ensure that all instances whereNewKeeper
is called are updated to pass these new dependencies to prevent potential runtime errors.Run the following script to find all usages of
NewKeeper
and check if they include the new parameters:Also applies to: 42-43
Verification successful
To gather the necessary information for a conclusive verification, we need to examine the
NewKeeper
function in the delegation module and its usage inapp/app.go
more closely. Let's run the following scripts:
To complete our verification, we need to extend the search context for the
DelegationKeeper
initialization inapp/app.go
. Let's run the following script:
Verification Successful: NewKeeper Dependencies Properly Updated
The
NewKeeper
constructor in the delegation module has been correctly updated to includeaccountKeeper
andbankKeeper
. The initialization ofDelegationKeeper
inapp/app.go
has also been properly updated to pass these new dependencies. No further changes are required.Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash # Description: Find all calls to NewKeeper and display them with context. # Test: Search for NewKeeper function calls. # Expect: All calls include accountKeeper and bankKeeper as arguments. rg --type go -A 3 -B 3 'NewKeeper\('Length of output: 13845
Script:
#!/bin/bash # Description: Examine the NewKeeper function in the delegation module and its usage in app/app.go # Check the NewKeeper function in the delegation module echo "Delegation Module NewKeeper:" rg --type go -A 10 'func NewKeeper\(' x/delegation/keeper/keeper.go # Check the initialization of DelegationKeeper in app/app.go echo "\nDelegationKeeper Initialization in app/app.go:" rg --type go -A 5 'app.DelegationKeeper =' app/app.goLength of output: 840
Script:
#!/bin/bash # Description: Examine the DelegationKeeper initialization in app/app.go with extended context echo "DelegationKeeper Initialization in app/app.go (extended context):" rg --type go -A 10 'app.DelegationKeeper =' app/app.goLength of output: 587
x/delegation/types/msg.go (2)
22-23
: Good use of centralized validation withvalidateDelegationInfo
By centralizing the validation logic in
validateDelegationInfo
, you enhance code reusability and maintainability.
53-53
: Consistent use of centralized validation inMsgUndelegation
Reusing
validateDelegationInfo
inMsgUndelegation
promotes consistency and reduces code duplication.x/assets/keeper/staker_asset.go (1)
102-113
: Non-deterministic iteration over mapsIterating over maps in Go does not guarantee order, which can cause non-deterministic behavior in blockchain applications. This issue has been previously identified and is still applicable.
x/delegation/keeper/delegation.go (4)
41-46
: Correct handling of non-native assetsThe code correctly checks for non-native assets and retrieves the staker's specified asset information with proper error handling.
48-50
: Proper validation of withdrawable amountThe validation ensures that the staker has sufficient withdrawable amount before proceeding with the delegation, which is implemented correctly.
52-58
: Staker asset state updated appropriatelyThe staker's asset state is updated by decreasing the withdrawable amount by the operation amount, and the error handling is properly managed.
59-64
: Correct delegation of native assetsThe code appropriately handles the delegation of native assets by constructing the coin and transferring it from the staker's account to the delegated pool with proper error handling.
x/delegation/keeper/delegation_op_test.go (1)
28-28
: Verify the initialization ofsuite.accAddr
At line 28,
suite.accAddr
is initialized usingsdk.AccAddress(suite.Address.Bytes())
. Please ensure thatsuite.Address
is properly initialized before this assignment to prevent potential issues with an uninitialized or incorrect address.app/app.go (7)
119-120
: Integration of vesting module imports is appropriateThe addition of the
vesting
module imports is correct for incorporating vesting functionalities.
253-253
: Include vesting module in ModuleBasicsAdding
vesting.AppModuleBasic{}
ensures the vesting module is properly registered inModuleBasics
.
284-286
: Verify module account permissions for delegation moduleThe
delegationTypes.DelegatedPoolName
is assigned bothauthtypes.Burner
andauthtypes.Staking
permissions. Please confirm that granting theauthtypes.Staking
permission is necessary and does not pose security risks.
541-541
: Ensure correct initialization of AssetsKeeper with DelegationKeeperThe
AssetsKeeper
now includes a reference to&app.DelegationKeeper
. Verify that this addition is required and that there are no circular dependency issues introduced.
549-550
: Addition of AccountKeeper and BankKeeper to DelegationKeeperIncluding
app.AccountKeeper
andapp.BankKeeper
in theDelegationKeeper
initialization ensures proper handling of accounts and balances within the delegation module.
811-811
: Add vesting module to the module managerIncluding
vesting.NewAppModule(app.AccountKeeper, app.BankKeeper)
integrates the vesting module into the application's module manager appropriately.
900-900
: Confirm vesting module's placement in module execution orderThe
vestingtypes.ModuleName
is added toSetOrderBeginBlockers
,SetOrderEndBlockers
, andSetOrderInitGenesis
. Please verify that its placement aligns with its dependencies and initialization requirements to prevent any unintended execution issues.Also applies to: 935-935, 980-980
x/reward/keeper/claim_reward.go (1)
143-151
: Previous comment is still valid
// don't update staker asset info for exo-native-token | ||
if assetID != assetstype.NativeAssetID { | ||
// todo: TotalDepositAmount might be influenced by slash and precision loss, | ||
// consider removing it, it can be recalculated from the share for RPC query. | ||
err = k.assetsKeeper.UpdateStakerAssetState(ctx, stakerID, assetID, assetstype.DeltaStakerSingleAsset{ | ||
PendingUndelegationAmount: removeToken, | ||
}) | ||
if err != nil { | ||
return removeToken, err | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Tip
Codebase Verification
Inconsistent handling of native asset detected
The conditional check for assetstype.NativeAssetID
before calling UpdateStakerAssetState
is not consistently applied across the codebase. While it's present in the reviewed file (x/delegation/keeper/share.go) and x/delegation/keeper/delegation.go, other occurrences of UpdateStakerAssetState
lack this check.
This inconsistency may lead to unexpected behavior in parts of the system that don't have this check. To ensure consistent handling of the native asset:
- Review all occurrences of
UpdateStakerAssetState
in the codebase. - Evaluate whether the conditional check for
assetstype.NativeAssetID
should be applied universally or if there are valid reasons for its absence in some cases. - Update the relevant functions to maintain consistency in native asset handling.
Analysis chain
Conditional check for exo-native token looks good!
The introduction of the conditional check to skip updating staker asset state for the exo-native token is a critical change for handling these assets. It alters the control flow and affects whether the UpdateStakerAssetState
method is called.
To ensure consistency, please run the following script to verify that skipping the update of staker asset state for the exo-native token aligns with other parts of the system:
Scripts executed
The following scripts were executed for the analysis:
Script:
#!/bin/bash
# Description: Verify consistency of skipping staker asset state update for exo-native token.
# Test 1: Search for other occurrences of `assetstype.NativeAssetID` and analyze the associated logic.
rg --type go -A 5 $'assetstype.NativeAssetID'
# Test 2: Search for `UpdateStakerAssetState` calls and check if they have similar conditional checks.
rg --type go -A 5 $'UpdateStakerAssetState'
Length of output: 13915
// new message to delegate asset to operator | ||
func NewMsgUndelegation(assetID, fromAddress string, amountPerOperator []KeyValue) *MsgUndelegation { | ||
baseInfo := &DelegationIncOrDecInfo{ | ||
FromAddress: fromAddress, | ||
PerOperatorAmounts: make([]KeyValue, 0, 1), | ||
} | ||
for _, kv := range amountPerOperator { | ||
baseInfo.PerOperatorAmounts = append(baseInfo.PerOperatorAmounts, KeyValue{Key: kv.Key, Value: kv.Value}) | ||
} | ||
return &MsgUndelegation{ | ||
AssetID: assetID, | ||
BaseInfo: baseInfo, | ||
} | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Optimize slice allocation in NewMsgUndelegation
Similar to NewMsgDelegation
, adjust the slice capacity of PerOperatorAmounts
to the length of amountPerOperator
for better performance.
Apply this diff to adjust the slice capacity:
- PerOperatorAmounts: make([]KeyValue, 0, 1),
+ PerOperatorAmounts: make([]KeyValue, 0, len(amountPerOperator)),
Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
// new message to delegate asset to operator | |
func NewMsgUndelegation(assetID, fromAddress string, amountPerOperator []KeyValue) *MsgUndelegation { | |
baseInfo := &DelegationIncOrDecInfo{ | |
FromAddress: fromAddress, | |
PerOperatorAmounts: make([]KeyValue, 0, 1), | |
} | |
for _, kv := range amountPerOperator { | |
baseInfo.PerOperatorAmounts = append(baseInfo.PerOperatorAmounts, KeyValue{Key: kv.Key, Value: kv.Value}) | |
} | |
return &MsgUndelegation{ | |
AssetID: assetID, | |
BaseInfo: baseInfo, | |
} | |
} | |
// new message to delegate asset to operator | |
func NewMsgUndelegation(assetID, fromAddress string, amountPerOperator []KeyValue) *MsgUndelegation { | |
baseInfo := &DelegationIncOrDecInfo{ | |
FromAddress: fromAddress, | |
PerOperatorAmounts: make([]KeyValue, 0, len(amountPerOperator)), | |
} | |
for _, kv := range amountPerOperator { | |
baseInfo.PerOperatorAmounts = append(baseInfo.PerOperatorAmounts, KeyValue{Key: kv.Key, Value: kv.Value}) | |
} | |
return &MsgUndelegation{ | |
AssetID: assetID, | |
BaseInfo: baseInfo, | |
} | |
} |
func validateDelegationInfo(assetID string, baseInfo *DelegationIncOrDecInfo) error { | ||
for _, kv := range baseInfo.PerOperatorAmounts { | ||
if _, err := sdk.AccAddressFromBech32(kv.Key); err != nil { | ||
return errorsmod.Wrap(err, "invalid operator address delegateTO") | ||
} | ||
if !kv.Value.Amount.IsPositive() { | ||
return errorsmod.Wrapf(ErrAmountIsNotPositive, "amount should be positive, got%s", kv.Value.Amount.String()) | ||
} | ||
} | ||
if assetID != assetstype.NativeAssetID { | ||
return errorsmod.Wrapf(ErrInvalidAssetID, "only nativeToken is support, expected:%s,got:%s", assetstype.NativeAssetID, assetID) | ||
} | ||
if _, err := sdk.AccAddressFromBech32(baseInfo.FromAddress); err != nil { | ||
return errorsmod.Wrap(err, "invalid from address") | ||
} | ||
return nil | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Correct typos and improve error messages in validateDelegationInfo
Several error messages contain typos or grammatical errors that could be clarified.
Apply the following diffs to correct the error messages:
- return errorsmod.Wrap(err, "invalid operator address delegateTO")
+ return errorsmod.Wrap(err, "invalid operator address to delegate to")
- return errorsmod.Wrapf(ErrAmountIsNotPositive, "amount should be positive, got%s", kv.Value.Amount.String())
+ return errorsmod.Wrapf(ErrAmountIsNotPositive, "amount should be positive, got %s", kv.Value.Amount.String())
- return errorsmod.Wrapf(ErrInvalidAssetID, "only nativeToken is support, expected:%s,got:%s", assetstype.NativeAssetID, assetID)
+ return errorsmod.Wrapf(ErrInvalidAssetID, "only native token is supported; expected: %s, got: %s", assetstype.NativeAssetID, assetID)
Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
func validateDelegationInfo(assetID string, baseInfo *DelegationIncOrDecInfo) error { | |
for _, kv := range baseInfo.PerOperatorAmounts { | |
if _, err := sdk.AccAddressFromBech32(kv.Key); err != nil { | |
return errorsmod.Wrap(err, "invalid operator address delegateTO") | |
} | |
if !kv.Value.Amount.IsPositive() { | |
return errorsmod.Wrapf(ErrAmountIsNotPositive, "amount should be positive, got%s", kv.Value.Amount.String()) | |
} | |
} | |
if assetID != assetstype.NativeAssetID { | |
return errorsmod.Wrapf(ErrInvalidAssetID, "only nativeToken is support, expected:%s,got:%s", assetstype.NativeAssetID, assetID) | |
} | |
if _, err := sdk.AccAddressFromBech32(baseInfo.FromAddress); err != nil { | |
return errorsmod.Wrap(err, "invalid from address") | |
} | |
return nil | |
} | |
func validateDelegationInfo(assetID string, baseInfo *DelegationIncOrDecInfo) error { | |
for _, kv := range baseInfo.PerOperatorAmounts { | |
if _, err := sdk.AccAddressFromBech32(kv.Key); err != nil { | |
return errorsmod.Wrap(err, "invalid operator address to delegate to") | |
} | |
if !kv.Value.Amount.IsPositive() { | |
return errorsmod.Wrapf(ErrAmountIsNotPositive, "amount should be positive, got %s", kv.Value.Amount.String()) | |
} | |
} | |
if assetID != assetstype.NativeAssetID { | |
return errorsmod.Wrapf(ErrInvalidAssetID, "only native token is supported; expected: %s, got: %s", assetstype.NativeAssetID, assetID) | |
} | |
if _, err := sdk.AccAddressFromBech32(baseInfo.FromAddress); err != nil { | |
return errorsmod.Wrap(err, "invalid from address") | |
} | |
return nil | |
} |
// new message to delegate asset to operator | ||
func NewMsgDelegation(assetID, fromAddress string, amountPerOperator []KeyValue) *MsgDelegation { | ||
baseInfo := &DelegationIncOrDecInfo{ | ||
FromAddress: fromAddress, | ||
PerOperatorAmounts: make([]KeyValue, 0, 1), | ||
} | ||
for _, kv := range amountPerOperator { | ||
baseInfo.PerOperatorAmounts = append(baseInfo.PerOperatorAmounts, KeyValue{Key: kv.Key, Value: kv.Value}) | ||
} | ||
return &MsgDelegation{ | ||
AssetID: assetID, | ||
BaseInfo: baseInfo, |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Optimize slice allocation in NewMsgDelegation
When initializing PerOperatorAmounts
, consider setting the slice capacity to match the length of amountPerOperator
to improve efficiency and avoid unnecessary allocations.
Apply this diff to adjust the slice capacity:
- PerOperatorAmounts: make([]KeyValue, 0, 1),
+ PerOperatorAmounts: make([]KeyValue, 0, len(amountPerOperator)),
Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
// new message to delegate asset to operator | |
func NewMsgDelegation(assetID, fromAddress string, amountPerOperator []KeyValue) *MsgDelegation { | |
baseInfo := &DelegationIncOrDecInfo{ | |
FromAddress: fromAddress, | |
PerOperatorAmounts: make([]KeyValue, 0, 1), | |
} | |
for _, kv := range amountPerOperator { | |
baseInfo.PerOperatorAmounts = append(baseInfo.PerOperatorAmounts, KeyValue{Key: kv.Key, Value: kv.Value}) | |
} | |
return &MsgDelegation{ | |
AssetID: assetID, | |
BaseInfo: baseInfo, | |
// new message to delegate asset to operator | |
func NewMsgDelegation(assetID, fromAddress string, amountPerOperator []KeyValue) *MsgDelegation { | |
baseInfo := &DelegationIncOrDecInfo{ | |
FromAddress: fromAddress, | |
PerOperatorAmounts: make([]KeyValue, 0, len(amountPerOperator)), | |
} | |
for _, kv := range amountPerOperator { | |
baseInfo.PerOperatorAmounts = append(baseInfo.PerOperatorAmounts, KeyValue{Key: kv.Key, Value: kv.Value}) | |
} | |
return &MsgDelegation{ | |
AssetID: assetID, | |
BaseInfo: baseInfo, |
parsedStakerID := strings.Split(record.StakerID, "_") | ||
stakerAddr := sdk.AccAddress(hexutil.MustDecode(parsedStakerID[0])) | ||
if err := k.bankKeeper.UndelegateCoinsFromModuleToAccount(ctx, types.DelegatedPoolName, stakerAddr, sdk.NewCoins(sdk.NewCoin(assetstypes.NativeAssetDenom, record.ActualCompletedAmount))); err != nil { | ||
panic(err) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Avoid panicking in EndBlock
; handle errors gracefully
Using panic
in the EndBlock
method can cause the entire blockchain to halt if an error occurs. Instead, return the error to handle it gracefully and maintain chain stability.
Apply this diff to replace the panic
with proper error handling:
- panic(err)
+ return nil, err
Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
panic(err) | |
return nil, err |
operatorAssetInfo, err := k.GetOperatorSpecifiedAssetInfo(ctx, sdk.MustAccAddressFromBech32(operator), assetID) | ||
if err != nil { | ||
return nil, errorsmod.Wrap(err, "failed to GetOperatorSpecifiedAssetInfo") | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Avoid potential panics by not using sdk.MustAccAddressFromBech32
Using sdk.MustAccAddressFromBech32
can lead to a panic if the operator address is invalid. To prevent this, use sdk.AccAddressFromBech32
and handle any errors gracefully.
Apply this diff to handle potential errors:
-operatorAssetInfo, err := k.GetOperatorSpecifiedAssetInfo(ctx, sdk.MustAccAddressFromBech32(operator), assetID)
+operatorAccAddr, err := sdk.AccAddressFromBech32(operator)
+if err != nil {
+ return nil, errorsmod.Wrapf(err, "invalid operator address: %s", operator)
+}
+operatorAssetInfo, err := k.GetOperatorSpecifiedAssetInfo(ctx, operatorAccAddr, assetID)
if err != nil {
return nil, errorsmod.Wrap(err, "failed to GetOperatorSpecifiedAssetInfo")
}
Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
operatorAssetInfo, err := k.GetOperatorSpecifiedAssetInfo(ctx, sdk.MustAccAddressFromBech32(operator), assetID) | |
if err != nil { | |
return nil, errorsmod.Wrap(err, "failed to GetOperatorSpecifiedAssetInfo") | |
} | |
operatorAccAddr, err := sdk.AccAddressFromBech32(operator) | |
if err != nil { | |
return nil, errorsmod.Wrapf(err, "invalid operator address: %s", operator) | |
} | |
operatorAssetInfo, err := k.GetOperatorSpecifiedAssetInfo(ctx, operatorAccAddr, assetID) | |
if err != nil { | |
return nil, errorsmod.Wrap(err, "failed to GetOperatorSpecifiedAssetInfo") | |
} |
// delegate exocore-native-token | ||
delegationParams = &delegationtype.DelegationOrUndelegationParams{ | ||
ClientChainID: assetstypes.NativeChainLzID, | ||
Action: types.DelegateTo, | ||
AssetsAddress: common.HexToAddress(assetstypes.NativeAssetAddr).Bytes(), | ||
OperatorAddress: opAccAddr, | ||
StakerAddress: suite.accAddr[:], | ||
OpAmount: sdkmath.NewInt(50), | ||
LzNonce: 0, | ||
TxHash: common.HexToHash("0x24c4a315d757249c12a7a1d7b6fb96261d49deee26f06a3e1787d008b445c3ac"), | ||
} | ||
err = suite.App.DelegationKeeper.DelegateTo(suite.Ctx, delegationParams) | ||
suite.NoError(err) | ||
// check delegation states | ||
stakerID, assetID = types.GetStakeIDAndAssetID(delegationParams.ClientChainID, delegationParams.StakerAddress, delegationParams.AssetsAddress) | ||
restakerState, err = suite.App.AssetsKeeper.GetStakerSpecifiedAssetInfo(suite.Ctx, stakerID, assetID) | ||
suite.NoError(err) | ||
balance := suite.App.BankKeeper.GetBalance(suite.Ctx, suite.accAddr, assetstypes.NativeAssetDenom) | ||
suite.Equal(types.StakerAssetInfo{ | ||
TotalDepositAmount: balance.Amount.Add(delegationParams.OpAmount), | ||
WithdrawableAmount: balance.Amount, | ||
PendingUndelegationAmount: sdkmath.NewInt(0), | ||
}, *restakerState) | ||
operatorState, err = suite.App.AssetsKeeper.GetOperatorSpecifiedAssetInfo(suite.Ctx, opAccAddr, assetID) | ||
suite.NoError(err) | ||
suite.Equal(types.OperatorAssetInfo{ | ||
TotalAmount: delegationParams.OpAmount, | ||
PendingUndelegationAmount: sdkmath.NewInt(0), | ||
TotalShare: sdkmath.LegacyNewDecFromBigInt(delegationParams.OpAmount.BigInt()), | ||
OperatorShare: sdkmath.LegacyNewDec(0), | ||
}, *operatorState) | ||
|
||
specifiedDelegationAmount, err = suite.App.DelegationKeeper.GetSingleDelegationInfo(suite.Ctx, stakerID, assetID, opAccAddr.String()) | ||
suite.NoError(err) | ||
suite.Equal(delegationtype.DelegationAmounts{ | ||
UndelegatableShare: sdkmath.LegacyNewDecFromBigInt(delegationParams.OpAmount.BigInt()), | ||
WaitUndelegationAmount: sdkmath.NewInt(0), | ||
}, *specifiedDelegationAmount) | ||
|
||
totalDelegationAmount, err = suite.App.DelegationKeeper.StakerDelegatedTotalAmount(suite.Ctx, stakerID, assetID) | ||
suite.NoError(err) | ||
suite.Equal(delegationParams.OpAmount, totalDelegationAmount) | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Refactor to reduce duplication in TestDelegateTo
The added code for delegating native tokens closely mirrors the existing delegation test. Consider refactoring to eliminate duplication by parameterizing the asset details or utilizing helper functions to handle common logic.
|
||
// undelegate exocore-native-token | ||
delegationEvent = suite.prepareDelegationNativeToken() | ||
|
||
err = suite.App.DelegationKeeper.UndelegateFrom(suite.Ctx, delegationEvent) | ||
suite.NoError(err) | ||
|
||
stakerID, assetID = types.GetStakeIDAndAssetID(delegationEvent.ClientChainID, delegationEvent.StakerAddress, delegationEvent.AssetsAddress) | ||
restakerState, err = suite.App.AssetsKeeper.GetStakerSpecifiedAssetInfo(suite.Ctx, stakerID, assetID) | ||
suite.NoError(err) | ||
balance := suite.App.BankKeeper.GetBalance(suite.Ctx, suite.accAddr, assetstypes.NativeAssetDenom) | ||
suite.Equal(types.StakerAssetInfo{ | ||
TotalDepositAmount: balance.Amount.Add(delegationEvent.OpAmount), | ||
WithdrawableAmount: balance.Amount, | ||
PendingUndelegationAmount: delegationEvent.OpAmount, | ||
}, *restakerState) | ||
|
||
operatorState, err = suite.App.AssetsKeeper.GetOperatorSpecifiedAssetInfo(suite.Ctx, delegationEvent.OperatorAddress, assetID) | ||
suite.NoError(err) | ||
suite.Equal(types.OperatorAssetInfo{ | ||
TotalAmount: sdkmath.NewInt(0), | ||
PendingUndelegationAmount: delegationEvent.OpAmount, | ||
TotalShare: sdkmath.LegacyNewDec(0), | ||
OperatorShare: sdkmath.LegacyNewDec(0), | ||
}, *operatorState) | ||
|
||
specifiedDelegationAmount, err = suite.App.DelegationKeeper.GetSingleDelegationInfo(suite.Ctx, stakerID, assetID, delegationEvent.OperatorAddress.String()) | ||
suite.NoError(err) | ||
suite.Equal(delegationtype.DelegationAmounts{ | ||
WaitUndelegationAmount: delegationEvent.OpAmount, | ||
UndelegatableShare: sdkmath.LegacyNewDec(0), | ||
}, *specifiedDelegationAmount) | ||
|
||
totalDelegationAmount, err = suite.App.DelegationKeeper.StakerDelegatedTotalAmount(suite.Ctx, stakerID, assetID) | ||
suite.NoError(err) | ||
suite.Equal(sdkmath.NewInt(0), totalDelegationAmount) | ||
|
||
records, err = suite.App.DelegationKeeper.GetStakerUndelegationRecords(suite.Ctx, stakerID, assetID) | ||
suite.NoError(err) | ||
suite.Equal(1, len(records)) | ||
UndelegationRecord = &delegationtype.UndelegationRecord{ | ||
StakerID: stakerID, | ||
AssetID: assetID, | ||
OperatorAddr: delegationEvent.OperatorAddress.String(), | ||
TxHash: delegationEvent.TxHash.String(), | ||
IsPending: true, | ||
BlockNumber: uint64(suite.Ctx.BlockHeight()), | ||
LzTxNonce: delegationEvent.LzNonce, | ||
Amount: delegationEvent.OpAmount, | ||
ActualCompletedAmount: delegationEvent.OpAmount, | ||
} | ||
UndelegationRecord.CompleteBlockNumber = UndelegationRecord.BlockNumber + delegationtype.CanUndelegationDelayHeight | ||
suite.Equal(UndelegationRecord, records[0]) | ||
|
||
suite.Ctx.Logger().Info("the complete block number is:", "height", UndelegationRecord.CompleteBlockNumber) | ||
waitUndelegationRecords, err = suite.App.DelegationKeeper.GetPendingUndelegationRecords(suite.Ctx, UndelegationRecord.CompleteBlockNumber) | ||
suite.NoError(err) | ||
suite.Equal(2, len(waitUndelegationRecords)) | ||
suite.Equal(UndelegationRecord, waitUndelegationRecords[0]) |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Eliminate repetitive code in TestUndelegateFrom
The new code segment for undelegating native tokens replicates existing logic. To enhance maintainability, refactor the test to use shared helper methods for common operations.
func (suite *DelegationTestSuite) prepareDelegationNativeToken() *delegationtype.DelegationOrUndelegationParams { | ||
delegationEvent := &delegationtype.DelegationOrUndelegationParams{ | ||
ClientChainID: assetstypes.NativeChainLzID, | ||
Action: types.DelegateTo, | ||
AssetsAddress: common.HexToAddress(assetstypes.NativeAssetAddr).Bytes(), | ||
OperatorAddress: suite.opAccAddr, | ||
StakerAddress: suite.accAddr[:], | ||
OpAmount: suite.delegationAmount, | ||
LzNonce: 0, | ||
TxHash: common.HexToHash("0x24c4a315d757249c12a7a1d7b6fb96261d49deee26f06a3e1787d008b445c3ac"), | ||
} | ||
err := suite.App.DelegationKeeper.DelegateTo(suite.Ctx, delegationEvent) | ||
suite.NoError(err) | ||
return delegationEvent | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Include operator registration in prepareDelegationNativeToken
The method prepareDelegationNativeToken
lacks the operator registration step present in prepareDelegation
. To prevent potential errors during delegation, ensure that the operator is registered before delegating native tokens.
Apply this diff to include operator registration:
func (suite *DelegationTestSuite) prepareDelegationNativeToken() *delegationtype.DelegationOrUndelegationParams {
+ registerReq := &operatortype.RegisterOperatorReq{
+ FromAddress: suite.opAccAddr.String(),
+ Info: &operatortype.OperatorInfo{
+ EarningsAddr: suite.opAccAddr.String(),
+ },
+ }
+ _, err := s.OperatorMsgServer.RegisterOperator(s.Ctx, registerReq)
+ suite.NoError(err)
delegationEvent := &delegationtype.DelegationOrUndelegationParams{
// existing code...
}
err := suite.App.DelegationKeeper.DelegateTo(suite.Ctx, delegationEvent)
suite.NoError(err)
return delegationEvent
}
Committable suggestion was skipped due to low confidence.
- ERC-20 Middleware | ||
- Recovery Middleware | ||
- IBC Transfer | ||
|
||
SendPacket, since it is originating from the application to core IBC: | ||
transferKeeper.SendPacket -> recovery.SendPacket -> erc20.SendPacket -> channel.SendPacket | ||
transferKeeper.SendPacket -> recovery.SendPacket -> erc20.SendPacket -> channel.SendPacket | ||
|
||
RecvPacket, message that originates from core IBC and goes down to app, the flow is the other way | ||
channel.RecvPacket -> erc20.OnRecvPacket -> recovery.OnRecvPacket -> transfer.OnRecvPacket | ||
channel.RecvPacket -> erc20.OnRecvPacket -> recovery.OnRecvPacket -> transfer.OnRecvPacket |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Update comments to reflect current transfer stack
The comments mention Recovery Middleware
, but it appears the recovery middleware is no longer part of the transfer stack. Please update the comments to accurately represent the current middleware configuration.
Apply this diff to correct the comments:
- // transfer stack contains (from bottom to top):
- // - ERC-20 Middleware
- // - Recovery Middleware
- // - IBC Transfer
+ // Transfer stack contains (from bottom to top):
+ // - ERC-20 Middleware
+ // - IBC Transfer
- transferKeeper.SendPacket -> recovery.SendPacket -> erc20.SendPacket -> channel.SendPacket
+ transferKeeper.SendPacket -> erc20.SendPacket -> channel.SendPacket
- channel.RecvPacket -> erc20.OnRecvPacket -> recovery.OnRecvPacket -> transfer.OnRecvPacket
+ channel.RecvPacket -> erc20.OnRecvPacket -> transfer.OnRecvPacket
Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
- ERC-20 Middleware | |
- Recovery Middleware | |
- IBC Transfer | |
SendPacket, since it is originating from the application to core IBC: | |
transferKeeper.SendPacket -> recovery.SendPacket -> erc20.SendPacket -> channel.SendPacket | |
transferKeeper.SendPacket -> recovery.SendPacket -> erc20.SendPacket -> channel.SendPacket | |
RecvPacket, message that originates from core IBC and goes down to app, the flow is the other way | |
channel.RecvPacket -> erc20.OnRecvPacket -> recovery.OnRecvPacket -> transfer.OnRecvPacket | |
channel.RecvPacket -> erc20.OnRecvPacket -> recovery.OnRecvPacket -> transfer.OnRecvPacket | |
// Transfer stack contains (from bottom to top): | |
// - ERC-20 Middleware | |
// - IBC Transfer | |
SendPacket, since it is originating from the application to core IBC: | |
transferKeeper.SendPacket -> erc20.SendPacket -> channel.SendPacket | |
RecvPacket, message that originates from core IBC and goes down to app, the flow is the other way | |
channel.RecvPacket -> erc20.OnRecvPacket -> transfer.OnRecvPacket |
Description
tasks
This PR add support for native token's delegation/undelegation, the assets info of native token will be taken care by bank/auth module, and delgation, operator info would still be maintained by assets module and delegation module. As for the staker info query from assets module we calculation the results using data from bank module.
Changes
Notable changes:
UpdateStakerAssetState
when it is exo-native-token relatedmap
with listCloses #XXX
Summary by CodeRabbit
New Features
Improvements
Constants
Refactor